title: How to preserve the value of thread variable in a multi-threaded program
body: <p>I have a code which spawns a new thread every 5 seconds and each thread periodically prints out the value of a counter. It starts up to 10 threads in total. </p>
  
  <p>Here's the code:</p>
  
  <pre><code>public static void main(String[] args) {
      ScheduledExecutorService task = Executors.newScheduledThreadPool(10);
      AtomicInteger counter = new AtomicInteger(0);
      int i = 0;
      while (i &lt; 10) {
          // sleep 5 seconds
          sleep(5);
          task.scheduleAtFixedRate(() -&gt; {
              String threadName = Thread.currentThread().getName();
              int newCounter = counter.get();
              System.out.println(String.format("[%s] counter = %d" , threadName, newCounter));
          }, 0, 2, TimeUnit.SECONDS);
  
          counter.getAndIncrement();
          ++i;
      }
  }
  
  private static void sleep(int sleepTime) {
      try {
          TimeUnit.SECONDS.sleep(sleepTime);
      } catch (InterruptedException ie) {
  
      }
  }
  </code></pre>
  
  <p>Here's the output:</p>
  
  <pre><code>[pool-1-thread-1] counter = 1
  [pool-1-thread-1] counter = 1
  [pool-1-thread-2] counter = 1
  [pool-1-thread-3] counter = 1
  [pool-1-thread-1] counter = 2
  [pool-1-thread-2] counter = 2
  [pool-1-thread-4] counter = 2
  [pool-1-thread-5] counter = 2
  [pool-1-thread-3] counter = 2
  [pool-1-thread-1] counter = 3
  [pool-1-thread-7] counter = 3
  [pool-1-thread-6] counter = 3
  [pool-1-thread-8] counter = 3
  [pool-1-thread-4] counter = 3
  [pool-1-thread-9] counter = 3
  [pool-1-thread-5] counter = 3
  [pool-1-thread-10] counter = 3
  [pool-1-thread-1] counter = 4
     .......
  </code></pre>
  
  <p>I want each thread to print out its original value, for example, pool-1-thread-1 should print out 0 or 1 (depending on whether counter gets incremented first or the thread starts first) all the time,  the second thread should emit previous counter + 1 persistently, ... such as follows:</p>
  
  <pre><code>[pool-1-thread-1] counter = 1
  [pool-1-thread-1] counter = 1
  [pool-1-thread-2] counter = 2
  [pool-1-thread-3] counter = 3
  [pool-1-thread-1] counter = 1
  [pool-1-thread-2] counter = 2
  [pool-1-thread-4] counter = 4
  [pool-1-thread-5] counter = 5
  [pool-1-thread-3] counter = 3
  [pool-1-thread-1] counter = 1
  [pool-1-thread-7] counter = 7
    .......
  </code></pre>
  
  <p>My question is how do I make the newCounter local variable keeps its original value in each thread. The way I can think of is to store the mapping of thread name to its original value in a thread-safe hash table. Is there any cleaner way to accomplish this? Thanks</p>