The analysis of Threadlocal

Source: Internet
Author: User
Tags log log


an overview

What Threadlocal is. Threadlocal is not a local implementation version of a thread, it is not a thread, but a threaded local variable-threadlocalvariable. Perhaps it would be more appropriate to name it Threadlocalvar. Threadlocal's function is very simple, that is, for each thread that uses the variable to provide a copy of the variable value, is a more special in Java thread binding mechanism, is that each thread can independently change its own copy, and not with the other threads of the replica conflict.

From a thread's point of view, each thread maintains an implicit reference to its thread local variable copy, as long as the thread is active and the threadlocal instance is accessible, and all copies of its thread-local instances are garbage collected (unless there are other references to those replicas) after the threads have disappeared.

Data accessed through threadlocal is always associated with the current thread, and the JVM binds private local instance access to each running thread, providing an isolation mechanism for concurrent access problems that often occur in multithreaded environments.

Threadlocal is how to maintain a copy of a variable for each thread. The idea is simple, there is a map in the Threadlocal class that stores a copy of the variables for each thread.

For multithreaded resource sharing issues,


The synchronization mechanism uses a time space-changing approach, providing only one variable, allowing different threads to queue for access.
Threadlocal uses space for time, each thread provides a variable, so it can be accessed simultaneously without affecting each other.





Two API description

ThreadLocal ()
Creates a thread-local variable.


T get ()
Returns the value in the current thread copy of this thread local variable, which is created and initialized if this is the first time a thread calls the method.


Protected T InitialValue ()
Returns the initial value of the current thread for this thread local variable. This method is called at most once per thread-local variable is obtained, the first time a thread accesses a variable using the Get () method. If the thread calls the set (T) method before the Get method, then the InitialValue method is not called in the thread. If the implementation returns NULL only, or if the programmer wants to initialize a thread-local variable to a value other than NULL, you must create a subclass for threadlocal and override this method. Typically, anonymous inner classes are used. A typical implementation of InitialValue will invoke an appropriate construction method and return the newly constructed object.


void Remove ()
Removes the value of this thread local variable. This may help reduce the storage requirements for thread-local variables. If you access this thread local variable again, it will have its initialvalue by default.


void set (T value)
Sets the value in the current thread copy of this thread local variable to the specified value. Many applications do not require this functionality, and they rely only on the InitialValue () method to set the value of a thread-local variable. The InitialValue method is generally overridden in a program to give a specific initial value.


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;
}
}



Three typical examples

Hiberante's session tool class Hibernateutil. This class is the Hibernateutil class in the official Hibernate document for session management.

public class Hibernateutil
{
private static log log = Logfactory.getlog (Hibernateutil.class);
private static final sessionfactory sessionfactory;

Static
{
Try
{
Create sessionfactory by default profile Hibernate.cfg.xml
Sessionfactory = new Configuration (). Configure (). Buildsessionfactory ();
}
catch (Throwable ex)
{
Log.error ("Initialization of Sessionfactory failed.) ", ex);
throw new Exceptionininitializererror (ex);
}
}


Create a thread local variable session to save Hibernate session
public static final ThreadLocal session = new ThreadLocal ();

Gets the session in the current thread
public static session Currentsession () throws Hibernateexception
{
Session S = (session) Session.get ();
if (s = = null)
{
Save the newly opened session to a thread local variable
s = sessionfactory.opensession ();
Session.set (s);
}
return s;
}

public static void CloseSession () throws Hibernateexception
{
Session S = (session) Session.get ();
Session.set (NULL);
if (s!= null)
S.close ();
}
}




Analyzing code


1 public static final ThreadLocal session = new ThreadLocal ();
2 public static session currentsession () {
3 Session S = (session) Session.get ();
4 if (s = = null) {
5 s = sessionfactory.opensession ();
6 Session.set (s);
7}
8 return s;
9}


General Analysis

Because the class does not override the Threadlocal InitialValue () method, the first time a thread local variable session is created, its initial value is null. The Get () method of the thread local variable is also null when the Currentsession () is invoked for the first time. So the session is judged. If NULL, a new session is opened and saved to the thread-local variable session, which is a critical step.


row by line analysis

First line
Class InitialValue is null if InitialValue is not initialized.

Third line
The session's get returns its corresponding thread internal variable based on the current thread, which means that the net.sf.hibernate.Session we need corresponds to each database connection. It is not safe to share database links in multi-threaded situations. Threadlocal ensures that each thread has its own s database connection.

Line Four
If the thread is first accessed, the natural s will be null, and then a session is created, specifically the fifth line.

Line Five
Create a database connection instance s.

Line Six
Save the database connection s to threadlocal.

Line Seventh
If the current thread has already accessed the database, get () from session gets () to obtain the connection instance that the thread last acquired.



Four Summary

The threadlocal use situation mainly solves the inconsistency problem of data due to concurrency in multiple threads. Threadlocal provides a copy of the data that is accessed concurrently in each thread.

Original post address: http://lavasoft.blog.51cto.com/62575/51926/



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.