Header javaperspective.com
JavaPerspective.com  >   Advanced Tutorials  >   4. Miscellaneous Java features  >   4.4. The class ThreadLocal

4.4. The class ThreadLocal
Last updated: 2 January 2013.

This tutorial will show you how and when to use the class ThreadLocal.

In a multithreaded application, ThreadLocal allows you to have a single instance of a given class per thread (a sort of per-thread singleton). This tutorial will show you how to implement such a per-thread singleton.

The class ThreadLocal encapsulates thread-local variables. A thread-local variable is a variable that has a distinct copy of itself for each thread that accesses it. Each thread can initialize (method initialValue), retrieve (method get), modify (method set) and remove (method remove) its copy of the variable regardless to what other threads are doing with their local copies.

Suppose that your multithreaded application requires the following set of utility methods (taken from the code exercice 5 and the JDOM and DOM integration tutorials):

// Returns true if the string argument can be parsed into a double value and false otherwise
public boolean isDouble(String str){
   
try{
         
Double.parseDouble(str);
         
return true;
   
}
   
catch(NumberFormatException e){
         
return false;
   
}
}


// Converts a JDOM document to a DOM document
public org.w3c.dom.Document jdomToDom(Document jdomDocument) throws JDOMException{
   
DOMOutputter outputter = new DOMOutputter();
   
return outputter.output(jdomDocument);
}


// Converts a DOM document to a JDOM document
public Document domToJDom(org.w3c.dom.Document domDocument){
   
DOMBuilder builder = new DOMBuilder();
   
return builder.build(domDocument);
}


// Other utility methods
// ...
// ...

Since these methods are called from numerous classes, you could be tempted to encapsulate them in a singleton. However, a singleton would degrade performance as the threads would have a serialized access to the singleton. That performance issue can be eliminated if you use a ThreadLocal to encapsulate the utility methods as shown in the code below:

import org.jdom2.Document;
import org.jdom2.JDOMException;
import org.jdom2.input.DOMBuilder;
import org.jdom2.output.DOMOutputter;


public final class UtilityMethods {

   
private DOMOutputter outputter;
   
private DOMBuilder builder;

   
//############################### Set up the ThreadLocal ###############################
    //###################################################################################
   
private static final ThreadLocal<UtilityMethods> instance = new ThreadLocal<UtilityMethods>(){
         
@Override
         
protected UtilityMethods initialValue(){
               
return new UtilityMethods();
         
}
    }
;

   
private UtilityMethods(){
         
outputter = new DOMOutputter();
          builder =
new DOMBuilder();
   
}

   
public static UtilityMethods getInstance(){
         
return instance.get();
   
}
   
//###################################################################################


    // returns true if the string argument can be parsed into a double value and false otherwise
   
public boolean isDouble(String str){
         
try{
               
Double.parseDouble(str);
               
return true;
         
}
         
catch(NumberFormatException e){
               
return false;
         
}
    }


   
// Converts a JDOM document to a DOM document
   
public org.w3c.dom.Document jdomToDom(Document jdomDocument) throws JDOMException{
         
return outputter.output(jdomDocument);
   
}


   
// Converts a DOM document to a JDOM document
   
public Document domToJDom(org.w3c.dom.Document domDocument){
         
return builder.build(domDocument);
   
}


   
// Other utility methods
    // ...
    // ...

}

The private constructor prevents other classes from instantiating UtilityMethods with the keyword new. To get a thread-local instance of UtilityMethods, a thread must call the static method getInstance which in turn calls the method get provided by the class ThreadLocal. If there is already an instance of UtilityMethods for the current thread, then the method get returns that instance. Otherwise, initialValue is called and a new instance of UtilityMethods is created and returned. Hence, there is a single instance of UtilityMethods per thread.

As an example, here is a call to the method isDouble:

boolean isDouble = UtilityMethods.getInstance().isDouble("33.7");
// do something with isDouble
// ...


You are here :  JavaPerspective.com  >   Advanced Tutorials  >   4. Miscellaneous Java features  >   4.4. The class ThreadLocal
Next tutorial :  JavaPerspective.com  >   Advanced Tutorials  >   4. Miscellaneous Java features  >   4.5. The class System

Copyright © 2013 - 2016. JavaPerspective.com. All rights reserved.  ( Terms | Contact | About ) 
Java is a trademark of Oracle Corporation
Image 1 Image 2 Image 3 Image 4 Image 5 Image 6 Image 7