ThreadLocal in Java-example program and Tutorial

Source: Internet
Author: User
Tags dateformat

ThreadLocal in Java is another-achieve thread-safety apart from writing immutable classes. If you had been writing multi-threaded or concurrent code in Java then you must being familiar with cost of synchronization or locking which can greatly affect Scalability of application, but there was no choice other than synchronize if you are S Haring objects between multiple threads. ThreadLocal in Java is a different-achieve thread-safety, it doesn ' t address synchronization requirement, instead I T eliminates sharing by providing explicitly copy of the Object to each thread. Since Object is no more gkfx there is no requirement of synchronization which can improve scalability and performance of Application. In this Java ThreadLocal Tutorial we'll see important points about ThreadLocal in Java, when to use ThreadLocal in Java And a simple Example of ThreadLocal in the Java program.

When to use ThreadLocal in Java

Many Java Programmer question where to use ThreadLocal in Java and some even argue benefit of ThreadLocal variable, but Th Readlocal have many genuine use cases and that's why their added in to standard Java Platform Library. I agree though until you is not in concurrent programming and you'll rarely use ThreadLocal. Below is some well know usage of ThreadLocal class in Java:

1) ThreadLocal is fantastic to implement per thread Singleton classes or per thread context information like transaction Id.

2) can wrap any non Thread Safe object in ThreadLocal and suddenly its uses becomes thread-safe, as it only being use D by Thread Safe. One of the classic example of ThreadLocal is sharing simpledateforamt. Since SimpleDateFormat is not thread safe, have a global formatter may not work but have per thread formatter would CER Tainly work.

3) ThreadLocal provides another to extend Thread. If you want to preserve or carry information from the one method call to another you can carry it by using ThreadLocal. This can provide immense flexibility as you don ' t need to modify any method.

On basic level ThreadLocal provides Thread confinement which is extension of local variable. While local variable is accessible on block they is declared, ThreadLocal is visible only in single Thread. No, the Thread can see each others ThreadLocal variable. Real Life Example of ThreadLocal is in Java EE application servers which uses Java ThreadLocal variable to keep track of Tra Nsaction and Security Context. It makes lot of sense to share heavy object like Database Connection as ThreadLocal in order to avoid excessive creation a nd cost of locking in case of sharing global instance.

Import java.io.ioexception;import java.text.dateformat;import java.text.simpledateformat;import  java.util.Date;/** * *  @author  */public class ThreadLocalTest {     public static void main (string args[])  throws ioexception  {        thread t1 = new thread (new  Task ());           thread t2 = new thread ( new task ());         t1.start ();         t2.start ();          }        /*     * thread safe format method  because every thread will use its own DateFormat      */  &Nbsp; public static string threadsafeformat (date date) {         dateformat formatter = perthreadformatter.getdateformatter ();         return formatter.format (date);     }}/* *  Thread Safe implementation of SimpleDateFormat * Each Thread  Will get its own instance of simpledateformat which will not  be shared between other threads. * */class perthreadformatter {     private static final ThreadLocal<SimpleDateFormat>  Dateformatholder = new threadlocal<simpledateformat> ()  {         /*         * initialvalue ()  is  called         */         @Override          protected simpledateformat initialvalue ()  {             system.out.println ("Creating simpledateformat for  Thread :  " + thread.currentthread (). GetName ());             return new simpledateformat ("dd/mm/yyyy");         }    };    /*      * every time there is a call for dateformat, threadlocal  will return calling     * thread ' s copy of  Simpledateformat     */    public static dateformat  getdateformatter () &NBSP;{&NBSP;&NBSp;      return dateformatholder.get ();     }}class  Task implements Runnable{        @Override      public void run ()  {        for (int i=0;  i<2; i++) {             System.out.println ("thread: "  + thread.currentthread (). GetName ()  +  " formatted  Date:  " + threadlocaltest.threadsafeformat (New date ())  );         }          }}output:creating  SimpleDateFormat for Thread : Thread-0Creating SimpleDateFormat for  thread : thread-1thread: thread-1 formatted date: 30/05/2012thread:  thread-1 formatted date: 30/05/2012thread: thread-0 formatted date: 30/05/2012 

If you look the output of above program than you'll find that when different thread calls Getformatter () method of Threa Dlocal class than its-InitialValue () method which creates exclusive instance of SimpleDateFormat for that Thread. Since SimpleDateFormat is isn't shared between thread and essentially local to the thread which creates it our Threadsaffo Rmat () method is completely thread-safe.

Important points on Java ThreadLocal Class

1. ThreadLocal in Java are introduced on JDK 1.2 but it later generified in JDK 1.4 to introduce type safety on ThreadLocal Variable.

2. ThreadLocal can associated with thread scope, all the code which are executed by Thread have access to ThreadLocal var Iables but the other thread can not see each others ThreadLocal variable.

3. Each thread holds a exclusive copy of ThreadLocal variable which becomes eligible to garbage collection after thread F Inished or died, normally or due to any Exception, Given those ThreadLocal variable doesn ' t has any other live references .

4. ThreadLocal variables in Java is generally private static fields in Classes and maintain their state inside Thread.

We saw how ThreadLocal on Java opens another avenue for Thread-safety. Though concept of Thread-safety by confining object to thread are there from JDK 1.0 and many programmer have there own Cust Om ThreadLocal classes, has ThreadLocal in the Java API makes it a lot more easy and standard. Think about ThreadLocal variable and designing concurrency in your application. Don ' t misunderstood that ThreadLocal are alternative of synchronization, it all depends upon design. If design allows each thread to has there own copy of object than ThreadLocal is there to use.

ThreadLocal in Java-example program and Tutorial

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.