title: Pre-initializing a pool of worker threads to reuse connection objects (sockets)
body: <p>I need to build a pool of workers in Java where each worker has its own connected socket; when the worker thread runs, it uses the socket but keeps it open to reuse later. We decided on this approach because the overhead associated with creating, connecting, and destroying sockets on an ad-hoc basis required too much overhead, so we need a method by which a pool of workers are pre-initializaed with their socket connection, ready to take on work while keeping the socket resources safe from other threads (sockets are not thread safe), so we need something along these lines...</p>
  
  <pre><code>public class SocketTask implements Runnable {
    Socket socket;
    public SocketTask(){
      //create + connect socket here
    }
  
    public void run(){
      //use socket here
    }
  </code></pre>
  
  <p>}</p>
  
  <p>On application startup, we want to initialize the workers and, hopefully, the socket connections somehow too... </p>
  
  <pre><code>MyWorkerPool pool = new MyWorkerPool();
  for( int i = 0; i &lt; 100; i++)
     pool.addWorker( new WorkerThread());
  </code></pre>
  
  <p>As work is requested by the application, we send tasks to the worker pool for immediate execution...</p>
  
  <pre><code>pool.queueWork( new SocketTask(..));
  </code></pre>
  
  <p><br>
  <b>Updated with Working Code</b><br>
  Based on helpful comments from Gray and jontejj, I've got the following code working...</p>
  
  <p><b>SocketTask</b><br></p>
  
  <pre><code>public class SocketTask implements Runnable {
      private String workDetails;
      private static final ThreadLocal&lt;Socket&gt; threadLocal = 
             new ThreadLocal&lt;Socket&gt;(){
          @Override
          protected Socket initialValue(){
              return new Socket();
          }           
      };
  
      public SocketTask(String details){              
          this.workDetails = details;
      }
  
      public void run(){      
          Socket s = getSocket(); //gets from threadlocal
          //send data on socket based on workDetails, etc.
      }
  
      public static Socket getSocket(){
          return threadLocal.get();
      }
  }
  </code></pre>
  
  <p><b>ExecutorService</b><br></p>
  
  <pre><code>ExecutorService threadPool = 
      Executors.newFixedThreadPool(5, Executors.defaultThreadFactory());
  
      int tasks = 15;  
      for( int i = 1; i &lt;= tasks; i++){
          threadPool.execute(new SocketTask("foobar-" + i));
      }   
  </code></pre>
  
  <p>I like this approach for several reasons...</p>
  
  <ul>
  <li>Sockets are local objects (via ThreadLocal) available to the running tasks, eliminating concurrency issues. </li>
  <li>Sockets are created once and kept open, reused
  when new tasks get queued, eliminating socket object create/destroy overhead.</li>
  </ul>