Java ThreadLocal is used to create thread local variables. We know that all threads of an Object share it’s variables, so the variable is not thread safe. We can use synchronization for thread safety but if we want to avoid synchronization, we can use ThreadLocal variables.

Java ThreadLocal

Every thread has it’s own ThreadLocal variable and they can use it’s get() and set() methods to get the default value or change it’s value local to Thread.

ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread.

Java ThreadLocal Example

Here is a small example showing use of ThreadLocal in java program and proving that every thread has it’s own copy of ThreadLocal variable.

ThreadLocalExample.java


Copy
package com.journaldev.threads; import java.text.SimpleDateFormat;
import java.util.Random; public class ThreadLocalExample implements Runnable{ // SimpleDateFormat is not thread-safe, so give one to each thread
private static final ThreadLocal<SimpleDateFormat> formatter = new ThreadLocal<SimpleDateFormat>(){
@Override
protected SimpleDateFormat initialValue()
{
return new SimpleDateFormat("yyyyMMdd HHmm");
}
}; public static void main(String[] args) throws InterruptedException {
ThreadLocalExample obj = new ThreadLocalExample();
for(int i=0 ; i<10; i++){
Thread t = new Thread(obj, ""+i);
Thread.sleep(new Random().nextInt(1000));
t.start();
}
} @Override
public void run() {
System.out.println("Thread Name= "+Thread.currentThread().getName()+" default Formatter = "+formatter.get().toPattern());
try {
Thread.sleep(new Random().nextInt(1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
//formatter pattern is changed here by thread, but it won't reflect to other threads
formatter.set(new SimpleDateFormat()); System.out.println("Thread Name= "+Thread.currentThread().getName()+" formatter = "+formatter.get().toPattern());
} }

Output of the above java ThreadLocal example program is:


Copy
Thread Name= 0 default Formatter = yyyyMMdd HHmm
Thread Name= 1 default Formatter = yyyyMMdd HHmm
Thread Name= 0 formatter = M/d/yy h:mm a
Thread Name= 2 default Formatter = yyyyMMdd HHmm
Thread Name= 1 formatter = M/d/yy h:mm a
Thread Name= 3 default Formatter = yyyyMMdd HHmm
Thread Name= 4 default Formatter = yyyyMMdd HHmm
Thread Name= 4 formatter = M/d/yy h:mm a
Thread Name= 5 default Formatter = yyyyMMdd HHmm
Thread Name= 2 formatter = M/d/yy h:mm a
Thread Name= 3 formatter = M/d/yy h:mm a
Thread Name= 6 default Formatter = yyyyMMdd HHmm
Thread Name= 5 formatter = M/d/yy h:mm a
Thread Name= 6 formatter = M/d/yy h:mm a
Thread Name= 7 default Formatter = yyyyMMdd HHmm
Thread Name= 8 default Formatter = yyyyMMdd HHmm
Thread Name= 8 formatter = M/d/yy h:mm a
Thread Name= 7 formatter = M/d/yy h:mm a
Thread Name= 9 default Formatter = yyyyMMdd HHmm
Thread Name= 9 formatter = M/d/yy h:mm a

As you can see from the output that Thread-0 has changed the value of formatter but still thread-2 default formatter is same as the initialized value. You can see the same pattern for other threads too.

Update: ThreadLocal class is extend in Java 8 with a new method withInitial() that takes Supplier functional interface as argument. So we can use lambda expressions to easily create the ThreadLocal instance. For example, above formatter ThreadLocal variable can be defined in one line as below:


Copy
private static final ThreadLocal<SimpleDateFormat> formatter =
ThreadLocal.<SimpleDateFormat>withInitial
(() -> {return new SimpleDateFormat("yyyyMMdd HHmm");});

If you are new to Java 8 features, please check out Java 8 Features and Java 8 Functional Interfaces.

That’s all for ThreadLocal in java programming.


Reference: API Doc


About Pankaj

If you have come this far, it means that you liked what you are reading. Why not reach little more and connect with me directly on Google Plus, Facebook or Twitter. I would love to hear your thoughts and opinions on my articles directly.

Recently I started creating video tutorials too, so do check out my videos on Youtube.

Java ThreadLocal Example(java中的ThreadLocal例子)的更多相关文章

  1. 谈谈Java中的ThreadLocal

    什么是ThreadLocal ThreadLocal一般称为线程本地变量,它是一种特殊的线程绑定机制,将变量与线程绑定在一起,为每一个线程维护一个独立的变量副本.通过ThreadLocal可以将对象的 ...

  2. Java中的ThreadLocal

    关于 ThreadLocal,我们经常用它来解决多线程并发问题,那它究竟是如何做到的?今天就让我们来好好看一下. 从源码入手 首先,让我们看看 ThreadLocal 类中的介绍: This clas ...

  3. Java中的ThreadLocal详解

    一.ThreadLocal简介 多线程访问同一个共享变量的时候容易出现并发问题,特别是多个线程对一个变量进行写入的时候,为了保证线程安全,一般使用者在访问共享变量的时候需要进行额外的同步措施才能保证线 ...

  4. Java中的ThreadLocal深入理解

    提到ThreadLocal,有些Android或者Java程序员可能有所陌生,可能会提出种种问题,它是做什么的,是不是和线程有关,怎么使用呢?等等问题,本文将总结一下我对ThreadLocal的理解和 ...

  5. 理解Java中的ThreadLocal

    提到ThreadLocal,有些Android或者Java程序员可能有所陌生,可能会提出种种问题,它是做什么的,是不是和线程有关,怎么使用呢?等等问题,本文将总结一下我对ThreadLocal的理解和 ...

  6. java 中的 ThreadLocal

    首先,ThreadLocal 不是用来解决共享对象的多线程访问问题的,一般情况下,通过ThreadLocal.set() 到线程中的对象是该线程自己使用的对象,其他线程是不需要访问的,也访问不到的.各 ...

  7. Java并发编程:深入剖析ThreadLocal(转载)

    Java并发编程:深入剖析ThreadLocal(转载) 原文链接:Java并发编程:深入剖析ThreadLocal 想必很多朋友对ThreadLocal并不陌生,今天我们就来一起探讨下ThreadL ...

  8. (转)Java并发编程:深入剖析ThreadLocal

    Java并发编程:深入剖析ThreadLoca Java并发编程:深入剖析ThreadLocal 说下自己的理解:使用ThreadLocal能够实现空间换时间,重在理解ThreadLocal是如何复制 ...

  9. Java并发编程:深入剖析ThreadLocal(转)

    目录大纲: 一.对ThreadLocal的理解 二.深入解析ThreadLocal类 三.ThreadLocal的应用场景 原文链接:http://www.cnblogs.com/dolphin052 ...

随机推荐

  1. WinRAR 5.21 去弹窗 疑惑

    WinRAR 突然就有弹窗广告了 ,找了个方法,重新写一下安装目录下的 rarreg.key,确实有效果但是重写的和之前的完全一样啊,至少在文本中完全一样,怎么回事. 下面附上两个文件, 1.key ...

  2. spring cloud config配置中心源码分析之注解@EnableConfigServer

    spring cloud config的主函数是ConfigServerApplication,其定义如下: @Configuration @EnableAutoConfiguration @Enab ...

  3. tomcat指定配置文件路径方法

    1.在catalina.sh 中设置JAVA_OPTS,例如: JAVA_OPTS='-server -Xms1024m -Xmx1024m -XX:NewSize=128m -XX:MaxPermS ...

  4. pwconv---pwunconv 密码投影

    pwconv命令用来开启用户的投影密码.Linux系统里的用户和群组密码,分别存放在名称为passwd和group的文件中, 这两个文件位于/etc目录下.因系统运作所需,任何人都得以读取它们,造成安 ...

  5. 今日 SGU 5.6

    SGU 106 题意:问你有多少个<x,y>,满足ax+by+c=0,x1<=x<=x2,y1<=y<=y2 收货:拓展欧几里得求解的是这种方程,ax+by=1,g ...

  6. C#之用户自定义控件

    一.新建用户自定义控件 如下图所示,想通过LED的点击来实现亮和灭使用去控制下位机. LED亮: LED灭: 首先新建一个用户控件类,如下图所示步骤: 在资源中,添加现有文件中加入图片 加入的图片可以 ...

  7. STM32上使用JSON

    一.STM32工程中添加JSON 最近在一网2串项目,串口和网口之间可能需要定义一下简单的通信协议,而通信协议上则需要去定义一下通信的数据格式,上次听剑锋说要用Json来定义,目前查了下资料具体如何去 ...

  8. 设计模式之禅——模板方法模式&钩子方法

    ** **板方法模式的定义: 定义一个操作的算法的框架,而将一些步骤延迟到子类中.使得子类可以不改变一个算法的框架即可重定义该算法的某些特定步骤. 例子:做一个简单的悍马车的模型 见UML图 一个抽象 ...

  9. Pig源代码分析: 简析运行计划的生成

    摘要 本文通过跟代码的方式,分析从输入一批Pig-latin到输出物理运行计划(与launcher引擎有关,通常是MR运行计划.也能够是Spark RDD的运行算子)的总体流程. 不会详细涉及AST怎 ...

  10. “此文件来自其他计算机,可能被阻止以帮助保护该计算机” 教你win7解除阻止程序运行怎么操作

    win7 批量解除可执行文件的锁定 "此文件来自其他计算机,可能被阻止以帮助保护该计算机" http://blog.csdn.net/gscsnm/article/details/ ...