Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should Java ThreadLocal variables be static

I was reading the JavaDoc for Threadlocal here

https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/ThreadLocal.html

and it says "ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread (e.g., a user ID or Transaction ID). "

But my question is why did they choose to make it static (typically) - it makes things a bit confusing to have "per thread" state but the fields are static?

like image 229
kellyfj Avatar asked May 06 '10 19:05

kellyfj


People also ask

Why do we need static variables in Java?

The static keyword in Java is mainly used for memory management. The static keyword in Java is used to share the same variable or method of a given class. The users can apply static keywords with variables, methods, blocks, and nested classes. The static keyword belongs to the class than an instance of the class.

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

It enables you to create variables that can only be read and write by the same thread. If two threads are executing the same code and that code has a reference to a ThreadLocal variable then the two threads can't see the local variable of each other.

Why is ThreadLocal needed?

ThreadLocal is useful, when you want to have some state that should not be shared amongst different threads, but it should be accessible from each thread during its whole lifetime. As an example, imagine a web application, where each request is served by a different thread.

When should ThreadLocal be removed?

You should always call remove because ThreadLocal class puts values from the Thread Class defined by ThreadLocal. Values localValues; This will also cause to hold reference of Thread and associated objects. the value will be set to null and the underlying entry will still be present.


2 Answers

Because if it were an instance level field, then it would actually be "Per Thread - Per Instance", not just a guaranteed "Per Thread." That isn't normally the semantic you're looking for.

Usually it's holding something like objects that are scoped to a User Conversation, Web Request, etc. You don't want them also sub-scoped to the instance of the class.
One web request => one Persistence session.
Not one web request => one persistence session per object.

like image 149
Affe Avatar answered Oct 04 '22 15:10

Affe


Either make it static or if you are trying to avoid any static fields in your class - make the class itself a singleton and then you can safely use the an instance level ThreadLocal as long as you have that singleton available globally.

like image 36
Adnan Memon Avatar answered Oct 04 '22 16:10

Adnan Memon