(1) ThreadLocal solves the problem of shared variables

1. Introduction to ThreadLocal                              

    "Water can carry a boat, it can also overwrite a boat", describing ThreadLocal as the most appropriate, because its original intention is to solve the problem of variable sharing when threads are concurrent, but due to excessive design, such as weak references and hash collisions, it is difficult to understand , High cost of use, but become a high incidence of failures, prone to memory leaks, dirty data, shared object updates and other problems. Maybe you think it covers the issue of shared variables, but it is not. The following analysis from the perspective of memory model, weak reference, hash algorithm:

2. ThreadLocal application scenario

Before discussing where ThreadLocal is used, let us make it clear that if there is only one thread, then there is no need to talk about ThreadLocal, ThreadLocal is used in a multi-threaded scenario! ! !

ThreadLocal is summarized in 2 types of uses:

  • Save thread context information, can be obtained wherever needed 

  • Thread-safe, to avoid certain situations need to consider the performance loss caused by thread safety must be synchronized! 

1. Introduction to Reference Types

    The reference held after the object is created on the heap is actually a variable type, and the reference chain can be formed by assigning values ​​between the references. Iterate from the GC Root to determine whether the reference is reachable. The reachability of the reference is the basic condition to determine whether it can be garbage collected. The stage of garbage collection can be determined according to the strength of the reference type semantics.

  1. Strong reference (Strong Reference): Object object = new Object (); such variable declaration and definition will produce a strong reference to the object. As long as the object has a strong reference point and the GC Root is reachable, when Java memory is reclaimed, the object will not be reclaimed even if the memory is nearing exhaustion.
  2. Soft Reference: Soft reference and weak reference, used in the scene of non-essential objects. Before the OOM , the garbage collector will add the objects pointed to by these references to the collection range to obtain

Guess you like

Origin blog.csdn.net/qq_41893274/article/details/105245459