Design and use of threadlocal in Java

Source: Internet
Author: User
Tags copy implement integer variables version variable thread access
When the design was launched in Java 1.2, a new support was introduced in the Java platform: java.lang.ThreadLocal, which provided us with a new option when writing multithreaded programming. This tool class can be very concise to write a graceful multithreaded program, although threadlocal is very useful, but seems to understand it now, the use of its friends are not many.

What's threadlocal?

What is threadlocal? In fact, Threadlocal is not a local implementation version of a thread, it's not a threads, it's thread local variable. Perhaps it would be more appropriate to name it Threadlocalvar. A thread-local variable (ThreadLocal) is very simple in that it provides a copy of the variable value for each thread that uses the variable, and each thread can independently alter its own copy without conflict with the replica of the other thread. From a thread's point of view, it's as if every thread owns the variable entirely. Thread-local variables are not a new Java invention, and in other language compiler implementations (such as IBM XL FORTRAN), it provides direct support at the language level. Because Java does not provide direct support at the language level, but rather provides a threadlocal class to support, the code to write thread-local variables in Java is relatively clumsy, perhaps one reason why thread-local variables are not well popularized in Java.

Design of Threadlocal

First look at the Threadlocal interface:

Object get (); Returns the thread local variable copy of the current thread protected Object initialvalue (); Returns the initial value of the current thread for this thread local variable
void set (Object value); Sets the value of a copy of the thread local variable for the current thread

Threadlocal has 3 methods, notably InitialValue (), which is a protected method that is explicitly implemented for subclass rewriting. This method returns the initial value of the current thread's local variable in the thread, which is a deferred invocation method that executes only 1 times when a thread calls get () or set (Object) for the 1th time. A true implementation in threadlocal returns a null directly:

Protected Object InitialValue () {return null;}
How does threadlocal maintain a copy of a variable for each thread? In fact, the idea of implementation is very simple, in the Threadlocal class has a map, used to store a copy of each thread's variables. For example, the following examples implement:

public class ThreadLocal
{
Private MAP values = Collections.synchronizedmap (new HashMap ());
Public Object Get ()
{
Thread curthread = Thread.CurrentThread ();
Object o = values.get (curthread);
if (o = = null &&!values.containskey (curthread))
{
o = InitialValue ();
Values.put (Curthread, O);
}
return o;
}

public void Set (Object newvalue)
{
Values.put (Thread.CurrentThread (), newvalue);
}

Public Object InitialValue ()
{
return null;
}
}
This is not an industrial strength, of course, but the overall idea of threadlocal in the JDK is similar.

The use of threadlocal

If you want thread-local variables to initialize other values, you need to implement threadlocal subclasses of your own and override the method, typically using an internal anonymous class to subclass Threadlocal, such as the following example, where the Serialnum class assigns an ordinal number to each class:

public class Serialnum
{
The next serial number to be assigned

private static int nextserialnum = 0;
private static ThreadLocal Serialnum = new ThreadLocal ()
{
Protected synchronized Object InitialValue ()
{
return new Integer (nextserialnum++);
}
};

public static int Get ()
{
Return ((Integer) (Serialnum.get ())). Intvalue ();
}
}
The use of the Serialnum class will be very simple because the get () method is static, so when you need to obtain the ordinal number of the current thread, simply call:

int serial = Serialnum.get ();
Can.

When a thread is active and the Threadlocal object is accessible, it holds an implied reference to a copy of the thread's local variable, and when the thread runs, a copy of the thread-local variables owned by that thread expires and waits for the garbage collector to collect it.

Comparison of threadlocal and other synchronization mechanisms

What are the advantages of threadlocal compared to other synchronization mechanisms? Threadlocal and all other synchronization mechanisms are to solve the multiple threads access to the same variable, in the ordinary synchronization mechanism, through the object lock to achieve multiple threads to the same variable security access. This variable is shared by multiple threads, and using this synchronization mechanism requires careful analysis of when to read and write variables, when to lock an object, when to release the object's locks, and so on. All of these are caused by multiple threads sharing resources. Threadlocal from another point of view to solve multi-threaded concurrent access, threadlocal will maintain a copy of each thread and the thread bound variable, thus isolating the data of multiple threads, each has its own copy of the variable, It is therefore not necessary to synchronize the variable. Threadlocal provides a thread-safe shared object that, when writing multithreaded code, encapsulates an entire variable that is unsafe, or encapsulates the thread-specific state of the object into the threadlocal.

Because you can hold objects of any type in threadlocal, the value of the current thread using threadlocal get is a mandatory type conversion. But as the new Java version (1.5) introduces the template, the new Threadlocal<t> class, which supports template parameters, will benefit. You can also reduce the forced type conversions and advance some error checking to the compile time, simplifying the use of threadlocal to a certain extent.

Summarize

Of course, threadlocal can not replace the synchronization mechanism, the two problems facing different areas. The synchronization mechanism is to synchronize multiple threads of concurrent access to the same resource, which is an effective way to communicate between multiple threads, while threadlocal is a data-sharing isolation of multiple threads, fundamentally not sharing resources (variables) between multiple threads, so of course there is no need to synchronize multiple threads. So, if you need to communicate between multiple threads, use the synchronization mechanism, and if you need to isolate a shared conflict between multiple threads, you can use threadlocal, which will greatly simplify your program, making the program easier to read and simpler.


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.