Understand the knowledge points:
Strong references: create references to objects
Soft references: application scenarios are in the cache
Weak references: application scenarios in transactions
Phantom references: application scenarios in direct memory management
ThreadLocal is thread isolation, each thread does not interfere with each other
import java.util.concurrent.TimeUnit;
public class hacker_01_ThreadLocalDemo {
public static ThreadLocal<User> th=new ThreadLocal<>();
public static void main(String[] args) throws InterruptedException {
// 第一个线程
new Thread(new Runnable() {
@Override
public void run() {
User user = new User();
user.setName("小凯");
user.setAge(1);
// set user data
th.set(user);
// get user data
User getUser=th.get();
System.out.println("第一个线程:"+getUser);
}
}).start();
// wait second thread run
TimeUnit.MILLISECONDS.sleep(1000);
// 第二个线程
new Thread(new Runnable() {
@Override
public void run() {
// get user data
User user=th.get();
System.out.println("第二个线程:"+user);
}
}).start();
}
}
result
From the result graph, it can be found that ThreadLocal has a natural thread isolation mechanism to ensure that the things of this thread can only be accessed and used by this thread.
What causes the isolation of ThreadLocal threads?
ThreadLocal set source code
Get a ThreadLocalMap, the stored key is the ThreadLocal object, and the value is the value to be stored.
ThreadLocal's getMap source code
threadLocals is a member variable of Thread, which ensures that threadLocals of different threads are different.
When threadLocals is null, call the createMap method
As can be seen from the above figure, the Entry object is stored in the map, the key in the Entry object is a weak reference type, and the value is a strong reference type.
The type of weak reference. If the ThreadLocal object in the memory is empty, the weak reference will point to null, which facilitates the recycling of the ThreadLoca object by the gc of the jvm and prevents memory leaks.