ThreadLocal in Java - Example Program and Tutorial

ThreadLocal in Java is another way to achieve thread-safety apart from writing immutable classes. If you have been writing multi-threaded or concurrent code in Java then you must be familiar with cost of synchronization or locking which can greatly affect Scalability of application, but there is no choice other than synchronize if you are sharing objects between multiple threads. ThreadLocal in Java is a different way to achieve thread-safety, it doesn‘t address synchronization requirement, instead it eliminates sharing by providing explicitly copy of Object to each thread. Since Object is no more shared there is no requirement of Synchronization which can improve scalability and performance of application. In this Java ThreadLocal tutorial we will see important points about ThreadLocal in Java, when to use ThreadLocal in Java and a simple Example of ThreadLocal in 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 ThreadLocal has many genuine use cases and that‘s why its added in to standard Java Platform Library. I agree though until you are not in concurrent programming, you will rarely use ThreadLocal. below are some well know usage of ThreadLocal class in Java:

1) ThreadLocal are fantastic to implement Per Thread Singleton classes or per thread context information like transaction id.

2) You can wrap any non Thread Safe object in ThreadLocal and suddenly its uses becomes Thread-safe, as its only being used by Thread Safe. One of the classic example of ThreadLocal is sharing SimpleDateForamt. Since SimpleDateFormat is not thread safe, having a global formatter may not work but having per Thread formatter will certainly work.

3) ThreadLocal provides another way to extend Thread. If you want to preserve or carry information from 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 only accessible on block they are declared, ThreadLocal are visible only in Single Thread. No two Thread can see each others ThreadLocal variable. Real Life example of ThreadLocal are in J2EE application servers which uses java ThreadLocal variable to keep track of transaction and security Context. It makes lot of sense to share heavy object like Database Connection as ThreadLocal in order to avoid excessive creation and 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
     */
    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() {
        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-0
Creating SimpleDateFormat for Thread : Thread-1
Thread: Thread-1 Formatted Date: 30/05/2012
Thread: Thread-1 Formatted Date: 30/05/2012
Thread: Thread-0 Formatted Date: 30/05/2012

If you look the output of above program than you will find that when different thread calls getFormatter() method of ThreadLocal class than its call its initialValue() method which creates exclusive instance of SimpleDateFormat for that Thread. Since SimpleDateFormat is not shared between thread and essentially local to the thread which creates its our threadSafFormat() method is completely thread-safe.

Important points on Java ThreadLocal Class

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

2. ThreadLocal can be associated with Thread scope, all the code which is executed by Thread has access to ThreadLocal variables but two thread can not see each others ThreadLocal variable.

3. Each thread holds an exclusive copy of ThreadLocal variable which becomes eligible to Garbage collection after thread finished or died, normally or due to any Exception, Given those ThreadLocal variable doesn‘t have any other live references.

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

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

时间: 2024-10-25 21:09:48

ThreadLocal in Java - Example Program and Tutorial的相关文章

JAVA学习篇--ThreadLocal,Java中特殊的线程绑定机制

在DRP项目中,我们使用了ThreadLocal来创建Connection连接,避免了一直以参数的形式将Connection向下传递(传递connection的目的是由于jdbc事务要求确保使用同一个connection连接).那么ThreadLocal是如果做到的呢?它和同步锁的不同在哪里? 是什么: 对于ThreadLocal看英文单词我们很容易理解为一个线程的本地实现,但是它并不是一个Thread,而是threadlocalvariable(线程局部变量).也许把它命名为ThreadLoc

How to Create a Java Concurrent Program

In this Document   Goal   Solution   Overview   Steps in writing Java Concurrent Program   Template Program:   Program Logic   Program Parameters   Database Operations   Setting request Completion Status   Register executable   Register Concurrent Pr

[转]POJO中使用ThreadLocal实现Java嵌套事务

大多嵌套事务都是通过EJB实现的,现在我们尝试实现对POJO的嵌套事务.这里我们使用了ThreadLocal的功能. 理解嵌套事务 事务是可以嵌套的.所以内层事务或外层事务可以在不影响其他事务的条件下进行回滚或提交. 新建的事务嵌套在外层事务中.如果内层事务完成(不论是回滚或是提交),外层的事务就可以进行回滚或提交,这样的操作并不会影响内层事务.首先关闭最内层的事务,并逐步移动到外层事务. 使用简单的POJO实现 新建如下接口: 1 importjava.sql.Connection; 2 3

Reading and writing files in Java (Input/Output) - Tutorial

Java Input Output This tutorial explains how to read and write files via Java. Table of Contents 1. Java I/O (Input / Output) for files 1.1. Overview 1.2. Reading a file in Java 1.3. Writing a file in Java 1.4. How to identify the current directory 2

akka---Getting Started Tutorial (Java): First Chapter

原文地址:http://doc.akka.io/docs/akka/2.0.2/intro/getting-started-first-java.html Introduction Welcome to the first tutorial on how to get started with Akka and Java. We assume that you already know what Akka and Java are and will now focus on the steps

帮助理解Java中ThreadLocal的一篇文章

原文地址:http://www.ahlinux.com/java/20332.html 并发编程中,一个重要的内容是数据共享.当你创建了实现Runnable接口的线程,然后开启使用相同Runnable实例的各种Thread对象,所有的线程便共享定义在Runnable对象中的属性.也就是说,当你在一个线程中改变任意属性时,所有的线程都会因此受到影响,同时会看到第一个线程修改后的值.有时我们希望如此,比如:多个线程增大或减小同一个计数器变量:但是,有时我们希望确保每个线程,只能工作在它自己的线程实例

Java Programming Tutorial Java Native Interface (JNI)

1.  Introduction At times, it is necessary to use native codes (C/C++) to overcome the memory management and performance constraints in Java. Java supports native codes via the Java Native Interface (JNI). JNI is difficult, as it involves two languag

Java并发(4):ThreadLocal

一.对ThreadLocal的理解 ThreadLocal是java.lang包中的一个类,很多地方叫做线程本地变量,也有些地方叫做线程本地存储,其实意思差不多.可能很多朋友都知道ThreadLocal为变量在每个线程中都创建了一个副本,那么每个线程可以访问自己内部的副本变量. 这句话从字面上看起来很容易理解,但是真正理解并不是那么容易.我们还是先来看一个例子: 1 class ConnectionManager { 2 3 private static Connection connect =

java并发之ThreadLocal

ThreadLocal为每个使用该变量的线程提供独立的变量副本,即每个线程内部都会有一个该变量,且在线程内部任何地方都可以使用,线程之间互不影响,这样一来就不存在线程安全问题,也不会严重影响程序执行性能.所以每一个线程都可以独立地改变自己的副本,而不会影响其它线程所对应的副本. 对比同步机制与ThreadLocal,可以得出同步通过加锁的方式实现了线程数据共享,也就是以时间换空间,而ThreadLocal则是以变量副本的方式通过以空间换时间的手段实现线程数据共享. ThreadLocal类提供的