[Java123] ThreadLocal study notes

https://www.cnblogs.com/ldq2016/p/9041856.html

 

When using ThreadLocal variable maintenance, ThreadLocal provided for each thread using the variable independent variable copy, each thread can independently change their copy without affecting other threads corresponding copy.

 

ThreadLocal interface methods

ThreadLocal class interface is very simple, only four methods, let's take a look:

  • Value void set (Object value) Sets the current thread's thread local variables.
  • public Object get () method returns the current thread corresponding to the thread-local variables.
  • public void remove () the value of the local variables of the current thread deleted, the purpose is to reduce memory usage, which is a new method for JDK 5.0. It should be noted that, when the end of the thread, the thread local variable should automatically be garbage, so explicitly call this method to clear the thread local variable is not required to operate, but it can speed up the recovery of memory speed.
  • protected Object initialValue () returns to the initial value of the thread local variables, which is a method of a protected, apparently to allow subclasses designed cover. This method is a method to delay calling, call get () or set (Object) when the execution thread the first time, and only performed once. The default ThreadLocal in direct returns a null.

ThreadLocal has support for generics, the class of the class name has become ThreadLocal <T>. API methods been adjusted accordingly, the new version of the API methods are void set (T value), T get () and T initialValue ().

 

In a class have ThreadLocal Map, for each of the stored copy of the variable thread, key elements of Map thread object, the copy of the variable corresponding to the value of the thread. We ourselves can provide a simple implementation version:

 

Guess you like

Origin www.cnblogs.com/cathygx/p/11285349.html