Threadlocal is not used to solve the problem of multi-thread access to shared objects. Generally, the objects in the thread through threadlocal. Set () are the objects used by the thread. Other threads do not need to be accessed or accessed.
Each thread has an independent object ??? The method of obtaining is to create an object through the new object operation in each thread. Each thread creates one object, not a copy or copy of any object.
Threadlocal. threadlocalmap: a custom hash map is only suitable for maintaining local thread values. It can only be used in threadlocal and does not provide external operations. Threadlocalmap belongs to the package level. The key in threadlocalmap uses weakreferences. (Hash table entries), when the reference queue is not used, the old entity will be recycled by GC (exclude other references to it)
Accessibility:
From the strongest to the weakest, different availability levels reflect the lifecycle of objects. You can define them as follows:
- If a thread can directly reach an object without traversing all referenced objects, the object is strongly accessible. The newly created object is strongly accessible to the thread that creates it.
- If an object is not strongly reachable but can be reached by traversing a soft reference, the object is soft reachable.
- If an object is neither strongly reachable nor soft reachable, but can be reached by traversing weak references, the object is weakly reachable. When a weak reference to a weak reachable object is cleared, the object can be terminated.
- If an object is neither strongly reachable nor soft reachable or weak reachable, it has been terminated and a virtual reference is used to reference it, the object is a virtual reachable object.
- Finally, when the method described above cannot reach an object, the object is not accessible, so the object can be recycled.
Threadlocal is suitable for Object Access by multiple threads (each thread corresponds to an instance), and this object is used in many places.