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:
- Is there value in running the Pen
object as threads? - If so, how would I pass data from
Author thread to Pen thread so that
the Pen thread can execute the read
(from author), write (to Paper), and
write back (back to invoking Author
thread) safely?
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
Callables (orRunnables if there is no need to return any result) instead of threads, and run them within theExecutorframework – this gives higher level abstractions to work with, resulting in cleaner and safer code.