First, ThreadLocal is not used to solve multi-threaded access problems with shared objects, and in general, objects in the thread through Threadlocal.set () are objects that the thread itself uses, and other threads do not need access or access. Different objects are accessed in each thread.
in addition,
It is said that threadlocal enables each thread to maintain its own independent object, not by Threadlocal.set (), but by creating an object through the operation of the new object in each thread, creating a copy or a copy of each thread that is not an object. The reference to this newly created object is saved to a map of each thread by Threadlocal.set (), each thread has a map that executes Threadlocal.get (), and each thread pulls the object from its own map and So the objects in their own thread are taken out, and the threadlocal instance is used as the key to the map.
If Threadlocal.set () goes in the same object that multiple threads share, then the Threadlocal.get () of multiple threads gets the shared object itself, or there is a concurrent access problem.
Summary: Threadlocal.set () in the object will exist in the current thread in a map, and the current ThreadLocal itself as a key, can only say that the map can guarantee the unique, the map of the object if it is stored through new, The object is unique to the thread if it is not persisted by another thread reference, otherwise there may be a multithreaded concurrency problem because it is a reference type
Test code:
public static ThreadLocal<String> threadLocal = new ThreadLocal<String>();
public static void main(String[] args) {
object [] objects = new object []{ 1 2 Span class= "pun" "}; &NBSP;
System.out.println(Arrays.toString(objects));
//
// for (int i = 0; i< 10 ;i++) {
//
// final int j= i ;
// new Thread(new Runnable() {
//
// @Override
// public void run() {
//
// threadLocal.set(j+"-----------"+Thread.currentThread().getId()+"-----"+threadLocal.hashCode());
// Thread.currentThread().getId();
// try {
// Thread.currentThread().sleep(1000);
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// System.out.println(threadLocal.get()+"----------"+Thread.currentThread().getId()+"------"+"-----"+threadLocal.hashCode());
// }
// }).start();
// }
ThreadLocal in Java