This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details

When and how to use ThreadLocal variables?

When should a ThreadLocal variable be used?

How to use it?

Answer:


A lot of knowledge points, really need to write out will master ! ! !   \color{purple} a lot of knowledge points, really need to write out just can master!! {~}

One possible (and common) use is when you have some objects that are not thread-safe, but you want to avoid synchronizing access to that object (for example, SimpleDateFormat). Instead, each thread is given its own object instance.

Such as:

public class Foo { // SimpleDateFormat is not thread-safe, so give one to each thread private static final ThreadLocal<SimpleDateFormat> formatter = new ThreadLocal<SimpleDateFormat>(){ @Override protected SimpleDateFormat initialValue() { return new SimpleDateFormat("yyyyMMdd HHmm"); }}; public String formatIt(Date date) { return formatter.get().format(date); }}Copy the code

Documentation.

Answer:

Many frameworks use ThreadLocals to maintain some context related to the current thread.

For example, when the current transaction is stored in ThreadLocal, you don’t need to pass it as a parameter through every method call in case someone on the stack needs to access it.

Web applications can store information about current requests and sessions in ThreadLocal so that the application can easily access them.

With Guice, you can use ThreadLocals when implementing custom scopes for injected objects (Guice’s default servlet scopes probably also use them).

ThreadLocals is a global variable (though less evil as they are limited to one thread), so care should be taken to avoid unnecessary side effects and memory leaks when using them. Design your API so that ThreadLocal values will always be cleared automatically when they are no longer needed, and the API will not be misused (for example, as shown below). ThreadLocals can be used to make the code cleaner and in some rare cases they are the only way to do anything (my current project has two such cases and they are both documented here under “Static Fields and global variables”).

The article translated from am2dgbqfb6mk75jcyanzabc67y ac4c6men2g7xr2a – stackoverflow – com. Translate. Goog/questions / 8…

I would use ThreadLocal to limit SimpleDateFormat to being shared within threads

Java string to date conversion? recommended

For example, for an operation log function, we need to use ThreadLocal to record the operator information of the current thread request.

It follows that our log tracking system will also use ThreadLocal

Of course ThreadLocal is used in many places. I opened a Spring project and used CTRL + SHIFT +F to find out about ThreadLocal


Welcome to my column S t a c k O v e r F l o w . I select the best questions and answers and test them frequently in interviews ! ! !   \color{red} Welcome to my column StackOverFlow, I will filter the quality of the interview test!! {~}


There are the latest and elegant ways to do this, and I will write my thoughts on this q&A at the end of the article \color{red} has the latest, elegant implementation, and I will also write my opinion on this question at the end of the article {~}

Thank you for reading this, if this article is well written and if you feel there is something to it

Ask for a thumbs up 👍 ask for attention ❤️ ask for share 👥 for 8 abs I really very useful!!

If there are any mistakes in this blog, please comment, thank you very much! ❤ ️ ❤ ️ ❤ ️ ❤ ️