Java ThreadLocal in principle with the use of scenario analysis

Today, the sharing of knowledge in Java ThreadLocal principle analysis and usage scenarios with you.

1 Java ThreadLocal in principle with the use of scenario analysis

What is ThreadLocal variable
ThreadLoal variables, thread-local variables, objects with a ThreadLocal included, they have different copies in different Thread. Here are a few points to note:

Because of its own copy of each instance of Thread, and the copy can only use by the current Thread. This is also the ThreadLocal was named after.

Since each instance has its own copy of Thread, Thread and other inaccessible, it would be shared among multiple threads is no problem.

ThreadLocal provides thread-local instances. It differs from ordinary variables that each thread will use the variable initialization a completely separate instance of copies. ThreadLocal variables are usually modified private static. At the end of a thread, all instances of ThreadLocal relative copy it uses can be recycled.

In general, the ThreadLocal applied to each thread needs its own separate instance and the instance to be used in multiple methods, i.e. variable inter-isolation method in a scene class sharing between threads.

The principle ThreadLocal
first ThreadLocal is a generic class, to ensure acceptable any type of object.

Because there can be multiple ThreadLocal objects within a thread, so they are actually ThreadLocal internal maintains a Map, HashMap this Map is not used directly, but ThreadLocal static inner class called ThreadLocalMap implementation.

And we use get (), set () method actually calls this ThreadLocalMap class corresponding get (), set () method.
set methods:

pu

Guess you like

Origin blog.csdn.net/weixin_45794138/article/details/104858983