I have a task that would benefit from the Thread Pool design pattern (many small tasks to be performed in parallel). I initially implemented a naive thread pool from scratch, with n Runnables all pulling work units from the same ConcurrentLinkedQueue
until the queue is empty, then terminating. I then decided "hey, let's try the Executor in Java, because that is probably better-tested and more reliable than my naively designed system." Problem: in my implementation, each thread persisted until the queue was empty, using a while (!queue.isEmpty())
, and got its own instance of a non-threadsafe object, let's call it SlowObject foo
, that is time-consuming to construct. Trying to pass all Runnable
s that go into the Executor
's pool an instance of the time-inefficient object fails because it is not thread-safe. Creating a new instance of SlowObject
for each Runnable
is undesirable because they are costly to construct.
Is there a way to say "how many threads are we using? Let's create one SlowObject
for each thread, and then let the Runnables detect what thread we're on and look up the correct object to use?" This sounds brittle and failure-prone -- not sure what design pattern I should be looking at instead, though.