Understanding the Threadlocal in Java

Source: Internet
Author: User
Tags dateformat

First, the threadlocal JDK API wrote: This class provides thread-local (thread-local) variables. These variables are different from their ordinary counterparts, because each thread that accesses a variable (through its Get or set method) has its own local variable, independent of the initialized copy of the variable. ThreadLocal instances are typically private static fields in a class that want to associate the state with a thread (for example, a user ID or transaction ID). Second, the combination of source understanding



You can see that the variables in the Threadlocal class have only these 3 int types:

Private final int threadlocalhashcode = Nexthashcode ();         private static Atomicinteger Nexthashcode = new Atomicinteger (); private static final int hash_increment = 0x61c88647;

The variables of the threadlocal instance are only static variables of the Threadlocalhashcode threadlocal class Nexthashcode and hash_increment actually hash_increment is a constant, indicating a connection The increment of the Threadlocalhashcode value for the two threadlocal instances that are being allocated, and Nexthashcode represents the Threadlocalhashcode value of the next threadlocal instance that is about to be allocated.
The Nexthashcode () method assigns the value of the next hashcode value of the Threadlocal class to the Threadlocalhashcode of the instance Nexthashcode, and then the Nexthashcode value increases Hash_ Increment this value.

private static int Nexthashcode () {return nexthashcode.getandadd (hash_increment); }

Threadlocal has a threadlocalmap static inner class that you can simply understand as a map, and this ' map ' copies a variable's ' copy ' of each thread stored therein.
Take a look at the set () method: Get a reference to the current thread, get a map of that thread from the map, or create and store a map if it has an updated cache value

public void Set (T value) {Thread T = Thread.CurrentThread ();         Threadlocalmap map = getmap (t);         if (map! = null) Map.set (this, value);     else Createmap (t, value); }

Take a look at the Get () method: First get the current thread reference, which is the key to get the response of the threadlocalmap, if this ' Map ' does not exist then initialize one, otherwise return the variable. Call the Get method if this map does not exist first initialize, create this map, place the thread as key, initialize the Vlaue into it, note the initialvalue here, we can override this method, initialize an appropriate value on the first call, and the default is NULL

Public T get () {Thread T = Thread.CurrentThread ();         Threadlocalmap map = getmap (t);             if (map! = null) {Threadlocalmap.entry E = map.getentry (this);         if (E! = null) return (T) E.value;     } return Setinitialvalue (); }

Private T Setinitialvalue () {T value = InitialValue ();         Thread t = Thread.CurrentThread ();         Threadlocalmap map = getmap (t);         if (map! = null) Map.set (this, value);         else Createmap (t, value);     return value; }

Protected T InitialValue () {return null; }

Let's look at the Threadlocalmap static inner class, the entry inside threadlocalmap  is WeakReference

Static Class Threadlocalmap {static Class Entry extends Weakreference<threadlocal> {/* * The value associated with this ThreadLocal.             */Object value;                 Entry (ThreadLocal K, Object v) {super (k);             Value = V; } } 。。。。。

Threadlocal is not related to multithreading concurrency. Threadlocal mode is to solve the cross-class cross-method calls within a single thread threadlocal is not used to solve the object sharing access problems, but mainly provides methods to persist the object and to avoid parameter passing the convenient way of object access. In general, objects that are passed through Threadlocal.set () to a thread are objects that the thread itself uses, and other threads do not need access or access.   Different objects are accessed in each thread. Iii. examples




Referring to Tim Cull's post "Simpledateformat:performance Pig" introduces Threadlocal's simple use, but also has a deep understanding of the use of SimpleDateFormat.  tim cull wrote:    tim Cull encountered a serious performance problem with SimpleDateFormat, which was mainly caused by SimpleDateFormat, creating a The overhead of SimpleDateFormat instances is expensive, and when parsing string times, creating instances with short life cycles frequently results in poor performance. Even if the SimpleDateFormat is defined as a static class variable, it seems to solve the problem, but SimpleDateFormat is non-thread-safe, the same problem exists, if the ' Synchronized ' thread synchronization also faces problems, and synchronization results in degraded performance (the acquisition of SimpleDateFormat instances of serialization between threads).     tim cull uses threadlocal to solve this problem, and for each thread SimpleDateFormat there is no state that affects the collaboration between them. Create a copy of the SimpleDateFormat variable for each thread, or a copy of the  import java.text.DateFormat;   import  java.text.parseexception;   import java.text.simpledateformat;   import  java.util.date;  /**   *  uses threadlocal to resolve simpledateformat thread-safety issues with space-time-swapping.    *  @author     *   */   public class dateutil {               private static final string date_format =  "Yyyy-mm-dd hh:mm:ss";                @SuppressWarnings ("Rawtypes")        private  static threadlocal threadlocal = new threadlocal ()  {            protected synchronized object initialvalue ()  {                return new  SimpleDateFormat (date_format);           }        };          public static DateFormat  GetDateFormat ()  {           return  (DateFormat)  threadlocal.get ();       }           Public static&nbsP;date parse (string textdate)  throws ParseException {            return getdateformat (). Parse (textDate);        }  }  creates a threadlocal class variable, which is created with an anonymous class that overrides the InitialValue method, and the primary function is to initialize the instance when it is created. You can also create the following method

 

    //first call get will return null       private static  Threadlocal threadlocal = new threadlocal ();       // Gets a copy of the variable for the thread, if the first get returns NULL if the InitialValue is not overwritten, it is necessary to initialize a SimpleDateFormat and set to Threadlocal         public static dateformat getdateformat ()         {            DateFormat df =  (DateFormat)   Threadlocal.get ();           if (df==null) {                df = new simpledateformat ( Date_format)                 Threadlocal.set (DF);           }            return df;       }   http://www.blogjava.net/lsbwahaha/archive/2011/ 10/29/362282.html  

Understanding Threadlocal in Java (go)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.