title: Java Executors and per-thread (not per-work unit) objects?
body: <p>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 <code>ConcurrentLinkedQueue</code> 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 <code>(!queue.isEmpty())</code>, and got its own instance of a non-threadsafe object, let's call it <code>SlowObject foo</code>, that is time-consuming to construct.  Trying to pass all <code>Runnable</code>s that go into the <code>Executor</code>'s pool an instance of the time-inefficient object fails because it is not thread-safe.  Creating a new instance of <code>SlowObject</code> for each <code>Runnable</code> is undesirable because they are costly to construct. </p>
  
  <p>Is there a way to say "how many threads are we using? Let's create one <code>SlowObject</code> 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.</p>