Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why ThreadLocal variable need to static?

I have read many articles on why ThreadLocal variable need to be static(although not necessary), but I didn't get the idea why it should be static.

I have read it here and many other links but didn't get the idea.

I have done something like this

public class ThreadLocalDemo{

    public static void main(String[]args)throws Exception{
        SharedRersource r1= new SharedRersource();
        Thread t1= new Thread(r1);
        Thread t2= new Thread(r1);
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println("Main thread Exiting...");
        }

    }

class SharedRersource implements Runnable{


        private ThreadLocal<Integer> threadId = new ThreadLocal(){
            protected Integer initialValue(){
                return (int)(Math.random()*100);
                }
        };
        public void run(){

            try{
                Thread.sleep(2000);
            }
            catch(InterruptedException e){
                e.printStackTrace();
                }
                System.out.println(threadId.get());

            }
        };

Here thread t1 and t2 is having private copy of threadId than why It should be static

Please give a better understanding to me. Thanks

like image 826
optional Avatar asked Mar 03 '16 06:03

optional


People also ask

Why ThreadLocal is static and final?

static final ThreadLocal variables are thread safe. static makes the ThreadLocal variable available across multiple classes for the respective thread only. it's a kind of Global variable decaration of the respective thread local variables across multiple classes.

What is the purpose of declaring a variable of type ThreadLocal?

The ThreadLocal class is used to create thread local variables which can only be read and written by the same thread. For example, if two threads are accessing code having reference to same threadLocal variable then each thread will not see any modification to threadLocal variable done by other thread.

How does ThreadLocal cause memory leak?

Memory leak is caused when ThreadLocal is always existing. If ThreadLocal object could be GC, it will not cause memory leak. Because the entry in ThreadLocalMap extends WeakReference, the entry will be GC after ThreadLocal object is GC.

Are ThreadLocal variables thread safe?

Java ThreadLocal is used to create thread local variables. We know that all threads of an Object share it's variables, so the variable is not thread safe. We can use synchronization for thread safety but if we want to avoid synchronization, we can use ThreadLocal variables.


1 Answers

Answer to this question lies into ThreadLocal implementation .

Think ThreadLocal as a container

ThreadLocal is a container that maintain a ThreadLocalMap internally , This ThreadLocalMap is the key why threadlocal need to be static(although not necessary ,but suggestion is keep it static).

Because we want single container per class , not container per instance .If we have container per instance we will be having as many container as instance and that will created memory leak .

More detail here

  1. http://www.0xcafefeed.com/2004/06/of-non-static-threadlocals-and-memory/
  2. https://www.appneta.com/blog/introduction-to-javas-threadlocal-storage/
like image 102
optional Avatar answered Sep 30 '22 17:09

optional