THREAD LOCAL

Thread Local


  • Thread Local

Example 1:


        
               package com.sdj.pack1;
               class ThreadL extends Thread
               {
                  ThreadLocal tl1;
                  ThreadL(ThreadLocal tl)
                  {
                     this.tl1=tl;   
                  }
                  public void run()
                  {
                     System.out.println(tl1.get());
                     tl1.set(20);
                     try
                     {
                        sleep(200);
                     }
                     catch(InterruptedException e)
                     {   }
                     System.out.println(tl1.get());
                     tl1.set(30);
                     System.out.println(tl1.get());
                  }
               }
               class ThreadL1 extends Thread
               {
                  ThreadLocal tl2;
                  ThreadL1(ThreadLocal tl)
                  {
                     this.tl2=tl;
                  }
                  public void run()
                  {
                     System.out.println(tl2.get());
                     try
                     {
                        sleep(200);
                     }
                     catch(InterruptedException e1)
                     {   }
                     System.out.println(tl2.get());
                     tl2.set(50);
                  }
               }
               public class ThLocale 
               {
                  public static void main(String[] args)
                  {
                     ThreadLocal tl=new ThreadLocal();
                     tl.set(5);
                     System.out.println(tl.get());
                     ThreadL tl1=new ThreadL(tl);
                     ThreadL1 tl2=new ThreadL1(tl);
                     tl1.start();
                     tl2.start();
                     System.out.println(tl.get());
                     tl.set(60);
                     System.out.println(tl.get());
                  }
               }        

   Output:

5 5 null 60 null 20 30 null

Explanation:

    set() method
    public void set(Object obj)
    {}
    get() method
    public Object get(Object obj)
    {}
  • ThreadLocal is one of the important concept in java.lang. package. It will act as local to each thread even multiple threads point working on to the same object.

  • It is not like normal global variables. For normal global variable object if more than one thread works on same object we will get data corruption.

  • But in ThreadLocal inside same object memory space it will partition the memory to each thread separately as below.

  • javapadho
    Thread Local