"Java Concurrency series 03" threadlocal Detailed

Source: Internet
Author: User
Tags garbage collection

First, preface

Threadlocal This object is for multi-threading, without multithreading threadlocal there is no need to exist. You can place any object that you want to have exclusive access to each thread and take it out at any time.

Ii. Basic Usage

The use of threadlocal is actually very simple:

    1. Create a static threadlocal in a class (equivalent to a factory class, because you want to create one to it when it is not available).
    2. Call its set and get methods elsewhere to hold the object.

Here's a sample:

 PackageYiwangzhibujian; Public classthreadlocaluse{//Create a static threadlocal object as a repository, storing each thread's own resources//instead of using object here, you can make the connection connection    Private StaticThreadlocal<object> store=NewThreadlocal<object>(); //call the Get method when each thread is getting a thread resource     PublicObject Get () {//first go to the warehouse to findObject obj=Store.get (); //If it doesn't exist, create one to the thread and put the created in the warehouse        if(obj==NULL) {obj=NewObject ();        Set (obj); }        returnobj; }        //To put a thread resource into the warehouse to call the Set method,     Public voidset (Object obj) {store.set (obj); }}

This is a usage template that can be changed depending on the situation.

Third, Threadlocal understand 3.1 threadlocal will cause memory leaks?

First make it clear that using threadlocal does not cause a memory leak. Now do the following test to prove this point, there are the following procedures:

 Public classthreadlocaltest{//create an object that Threadlocal uses to store each thread    Private StaticThreadlocal<object> local=NewThreadlocal<object>(); //A constant that is used to create an object of 10M size using    Private Static Final int_1mb=1024*1024;  Public Static voidMain (string[] args)throwsexception{//Create a Runnable objectRunnable r=NewRunnable () {@Override Public voidrun () {System.out.println ("Range creates objects and places them in threadlocal"); //create an array of 10M size and drop it into threadlocal                byte[] Data=New byte[10*_1MB];                Local.set (data); System.out.println ("The child thread ends, represents the thread end");        }        }; //Create a thread and runThread t=NewThread (R);                T.start (); System.out.println ("The main thread sleeps for one second, in order to have the child threads created complete"); Thread.Sleep (1000); System.out.println ("Hibernate complete, main thread ready to allocate an array of 10M size"); byte[] data2=New byte[10*_1MB]; System.out.println ("Allocate array Complete"); }}

In the program right click on Run As->run configurations for virtual machine configuration:

The configuration is as follows,-xx:+printgcdetails (print garbage collection Log)-xx:+printgctimestamps (print recycle time, can not be used)-xms18m-xmx18m (set initialization and maximum memory is 18M, this is done to When creating an array of two 10M sizes, memory overflows or recycles within threadlocal):

The goal of this program is to create an object to be placed in the threadlocal to see if the garbage collector will recycle it at the end of the thread. The results of the operation are as follows:

The main thread sleeps for one second, in order for the child thread to be created to complete the range to create the object and place the threadlocal the child thread to run the end, which represents the end of the thread completion of hibernation, the main thread prepares to allocate an array of 10M size1.102:[GC [psyounggen:376k->224k (5376K)]10616k->10464k (17664K), 0.0077785 secs][times:user=0.03 sys=0.00, real=0.01 secs]1.110:[GC [psyounggen:224k->224k (5376K)]10464k->10464k (17664K), 0.0008971 secs][times:user=0.00 sys=0.00, real=0.00 secs]1.111:[Full GC [psyounggen:224k->0k (5376K)] [psoldgen:10240k->164k (12288K)]10464k->164k (17664K)[pspermgen:3030k->3030k (21248K)], 0.0058052 secs][times:user=0.00 sys=0.00, real=0.00 secs]Allocation Array Complete

It can be found that when the main thread is ready to allocate an array of 10M size, the memory is not enough, the garbage processor is called to recycle, and the objects placed in threadlocal are recycled by [psoldgen:10240k->164k (12288K)].

3.2 Replacing threadlocal with a global map can

I've also wanted to replace threadlocal with a global map, which is a sample of the presentation using the following code:

 Public classthreadlocaluse{Private StaticMap<thread,object> store=NewHashmap<thread,object>(); //call the Get method when each thread is getting a thread resource     PublicObject Get () {//first go to the warehouse to findObject obj=Store.get (Thread.CurrentThread ()); //If it doesn't exist, create one to the thread and put the created in the warehouse        if(obj==NULL) {obj=NewObject ();        Set (obj); }        returnobj; }        //To put a thread resource into the warehouse to call the Set method,     Public voidset (Object obj) {store.put (Thread.CurrentThread (), obj); }}

This can also be done within the thread to share objects, but there is a fatal disadvantage, that is, when the thread ends, the objects stored in the map must be manually purged, otherwise it will cause a memory leak.

3.3 Comparison of threadlocal and synchronized synchronization mechanisms

A lot of people are going to compare these two objects, and I'll talk about my own ideas.

Using synchronized is to atomically manipulate multiple statements, and any one thread executes code to ensure that other threads cannot execute the code, rather than i++ the increment operation, otherwise it will produce dirty data, which can be avoided by using synchronized.

The use of threadlocal is used to store objects for each thread. Since each thread uses its own object, there is no multithreading-related problem without competition.

3.5 I have a little understanding of threadlocal

Originally, I have been thinking threadlocal design has a little bit unreasonable, such as why can only store an object, store multiple objects how good, or thread directly built a map how good, you can do this:

Thread.CurrentThread (). Map.put (Key,value); Thread.CurrentThread (). Map.get (key);

I think I have a good idea, but as for why the design might mean something different.

This article explains the threadlocal, although it does not have much to do with concurrency, but it is due to multithreading, it is still related to it.

No reprint without permission.

"Java Concurrency series 03" threadlocal Detailed

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.