Reputation: 540
My rule of thumb about using thread is: if multiple instances of the same object needs to run concurrently, use threads. But I am facing the design choice issue in a scenario similar to the one I am describing below. Please help me clarify this once and for all:
(Reusing the example from my previous post)
I have 5 Pen object instances, 100 Author threads, and 3 Paper object instances.
Any number of Authors may be using any number of Pens to write on any given paper.
I have created blocking queue to protect the Pen objects being accessed by Authors.
If all pens in the queue are used, Authors wait.
The Pen instances take data from Author threads and append it to the (specified) Paper instance.
After updating Paper instance, Pen also updates the invoking Author thread.
Questions:
Upvotes: 0
Views: 1351
Reputation: 116266
My first take would be that Authors are workers (i.e. possibly threads), while pen and paper are resources (i.e. no threads - only used by some workers).
I would refactor the design to move the functionality from Pens to Authors. Also I would try to model Authors as Callable
s (or Runnable
s if there is no need to return any result) instead of threads, and run them within the Executor
framework - this gives higher level abstractions to work with, resulting in cleaner and safer code.
Upvotes: 2