A concept of ThreadLocal

ThreadLocal is a private thread variable, as the name suggests

ThreadLocal source code analysis

private void set(ThreadLocal key, Object value) { // We don't use a fast path as with get() because it is at // least as common to use set() to create new  entries as // it is to replace existing ones, in which case, a fast // path would fail more often than not. Entry[] tab = table; int len = tab.length; int i = key.threadLocalHashCode & (len-1);Copy the code

We see that his data structure is actually an array of hash tables, which reminds us of our old friend HashMap, but, hey, they are different. So let’s look at the array that it’s made up of, and the array is of type Entry, what is this thing, let’s look at its source code

static class Entry extends WeakReference { /** The value associated with this ThreadLocal. */ Object value; Entry(ThreadLocal k, Object v) { super(k); value = v; }}Copy the code

Three reference categories

Do you see the inheritance of WeakReference? Do you guys know what he is? It is one of several types of Java references that are strong, soft, weak, and virtual

  • Strong reference

    Object obj = new Object(); Object objects are not recycled as long as obj points to Object objectsCopy the code

    As long as strong references exist, the garbage collector will never reclaim the referenced object, even if memory is low, and the JVM will simply throw OutofMemoryErrors without collecting them. If you want to break the connection between a strong reference and an object, you can explicitly assign a strong reference to NULL so that the JVM can reclaim the object in time

  • Soft references

    SoftReference<byte[]> sr = new SoftReference<>(buff);
    Copy the code

    Soft references are used to describe objects that are not necessary but still useful. If the memory is insufficient, the system will reclaim the soft reference object. If the memory is insufficient, the system will throw an out of memory exception. This feature is often used to implement caching techniques, such as web caching, image caching, etc

  • A weak reference

    Weak references have weaker reference strength than soft references, and as soon as the JVM starts garbage collection, objects associated with weak references will be collected, regardless of whether memory is sufficient. After JDK1.2, using Java. Lang. Ref. WeakReference weak references

  • Phantom reference

    PhantomReference is a weak reference that cannot be used to retrieve an object once it has been defined. The only purpose of setting a virtual reference to an object is to receive a system notification when the object is reclaimed.

Here we see that the reference selected by ThreadLocal is weak, but there are some problems with this, which will be explained in more detail in future updates