References and threadlocal in Java

Source: Internet
Author: User


ThreadLocal


A few days ago saw @ Kim's threadlocal blog deep Feelings, all in this once again summed up my understanding of the source of threadlocal, as well as the internal mechanism.


Data


Here's a look at the ThreadLocal data structure: Every thread has a threadlocal.threadlocalmap threadlocals object inside, and In Threadlocalmap , a entry[] array is maintained, each entry object containing a weakly referenced threadlocal and a value.





Internal mechanisms


Set operation


  Public voidset (T value) {//gets the current threadThread T =Thread.CurrentThread (); //based on the current thread, locate the Threadlocalmap inside the threadThreadlocalmap map =Getmap (t); if(Map! =NULL)//assigns the current threadlocal and valueMap.set ( This, value); Else //Create a threadlocalmap inside a threadCreatemap (t, value); } 


Get operation


 PublicT Get () {Thread T=Thread.CurrentThread (); Threadlocalmap Map=Getmap (t); if(Map! =NULL) { //according to the current threadlocal key, get the corresponding entry and get the valueThreadlocalmap.entry e = Map.getentry ( This); if(E! =NULL) {@SuppressWarnings ("Unchecked") T result=(T) E.value; returnresult; }        } //returns the default value returnSetinitialvalue (); }
Principle Analysis


1) Why Threadlocalmap use WeakReference to encapsulate key?


 static  class  Entry extends  weakreference<threadlocal<?>> { /**   The value associated with this ThreadLocal.  */  Object value; Entry (ThreadLocal  <?> K, Object v) {  Super   (k);         Value  = V; }    }
WeakReference has the following characteristics: When an object A has only a weakreference reference to it, then a is recycled at the next GC. Imagine, if a key in the THREADLOCALMAP has not been used, and eventually there will only be a weakreference point to it, this key can naturally be recycled, will not remain in the Threadlocalmap.  (the reference will be described in more detail later) if the threadlocal is recycled, then how is the value recycled? In the Get and set methods of the Threadlocalmap, according to threadlocal through the hash, gets to the entry, if the entry Key=null, executes the expungestaleentry (i) method, The main operation of this method is to clean up the useless data at the current location of the hash table (and, of course, other actions). In summary, assuming that an Threadlocal object is not valid, the object itself will be reclaimed at the next GC, and the corresponding value value will be released in a threadlocal call, and if a thread dies, its corresponding threadlocal content is automatically freed. 2) Why use an open address to achieve hash conflicts? Threadlocalmap entry[] Table tables are different from HashMap's linked-list method to resolve conflicts.


A. Save memory space, the list uses more space than the array;
B. Hash key designed by Threadlocalmap can avoid hash collisions as much as possible;
C. The efficiency of cleaning data is high, after all, traversing the array is more efficient than traversing the linked list;


References in Java


In an in-depth understanding of the JVM, we talked about strong references, soft references, weak references, and virtual references. However, I did not go into the study at that time, the following is a detailed summary of Java references.


Weakhashmap


Before introducing the reference, let's take a look at the implementation principle of Weakhashmap, first give the following test cases,


 Public classTest { Public Static voidMain (string[] args) {Map<integer, object> map =NewHashmap<>();  for(inti = 0; I < 10000; i++) {Integer II=NewInteger (i); Map.put (II,New byte[i]); }  }}//Memory OverflowException in thread "main"Java.lang.OutOfMemoryError:Java Heap space at Com.test.test.main (Test.java:18)//change HashMap to WeakhashmapWithout any error


In fact, Weakhashmap specifies a weak key, and when only one weak reference points to that key, the domain is cleared at the next GC when there is not enough memory. In addition, in Weakhashmap's set (), get (), size () operation, the Expungestaleentries () method is called indirectly or directly to clean up the table entry that holds the weak reference key.


  Private Static classEntry<k,v>extendsWeakreference<object>ImplementsMap.entry<k,v>{V value; Final intHash; Entry<K,V>Next; /*** Creates new entry. */Entry (Object key, V value, Referencequeue<Object>Queue,intHash, entry<k,v>next) { Super(key, queue);  This. Value =value;  This. hash =Hash;  This. Next =Next; } 
Soft references and weak references


The use of references is extensive and is not described in terms of strong and false references, with a focus on two references, soft references, and weak references.



Look at the following example:


 Public classTest { Public Static voidMain (string[] args) {/*Test1*/Pojo Pojo=NewPojo ("Test1"); WeakReference<Pojo> sr =NewWeakreference<pojo>(Pojo); //If you add the following soft-reference, the soft reference will delete the object only if the memory is low, and all will print Test1//softreference<pojo> SF = new softreference<pojo> (Pojo);Pojo =NULL; //at this point, only one weak reference points to the objectSystem.GC ();   System.out.println (Sr.get ()); //NULL } Static classPojo {String value; Pojo (String value) { This. Value =value; }  PublicString toString () {return  This. Value; }  }}
Summarize WeakReference: Each time a GC, if an object A is only weakreference direct reference, then a can be recycled;
SoftReference: When the memory is low (in fact, and weakreference almost), if an object A is only softreference or weakreference directly referenced, then a can be recycled;
Note: When there is not enough memory or GC, the reference object itself is not recycled, but the object referenced by reference.






References and threadlocal in Java


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.