This discussion is archived
4 Replies Latest reply: May 2, 2007 11:50 PM by 791266 RSS

Benefits of ThreadLocal?

807599 Newbie
Currently Being Moderated
Hi, I'm trying to understand the benefits of the ThreadLocal class but I don't understand. I've got the following code:
package uk.co.jemos.experiments;



public class SerialNum {
     // The next serial number to be assigned
     private static int nextSerialNum = 0;

     private static ThreadLocal serialNum = new ThreadLocal() {
         protected synchronized Object initialValue() {
             return new Integer(nextSerialNum++);
         }
     };

     public static int get() {
         return ((Integer) (serialNum.get())).intValue();
     }
     
     
     public static void main(String[] args) {
          Runnable run = new Runnable() {
               int serialNum = 0;
               public void run() {
                    serialNum = SerialNum.get();
                    System.out.println(Thread.currentThread().getName() + 
                              " serial num before loop: " + serialNum);
                    for (int i = 0; i < 10; i++) {
                         serialNum = SerialNum.get();
                    }
                    System.out.println(Thread.currentThread().getName() + 
                              " serial num after loop: " + serialNum);
               }
          };
          
          Thread[] threads = new Thread[5];
          Thread t = null;
          for (int i = 0; i < 5; i++) {
              t = new Thread(run, "Thread:" + i);
              threads[i] = t;
          }
          for (Thread th: threads) {
               th.start();
          }
     }
     
 }
Which produces the following output:

Thread:0 serial num before loop: 0
Thread:0 serial num after loop: 0
Thread:1 serial num before loop: 1
Thread:1 serial num after loop: 1
Thread:2 serial num before loop: 2
Thread:2 serial num after loop: 2
Thread:3 serial num before loop: 3
Thread:3 serial num after loop: 3
Thread:4 serial num before loop: 4
Thread:4 serial num after loop: 4

Does the above mean that everytime serialNum.get() is invoked a new variable local to the thread is created with value zero? I would have expected that after the first time, invocation to serialNum.get would return nextSerialNum+1.