- 浏览: 148225 次
- 性别:
- 来自: 北京
文章分类
- 全部博客 (110)
- CoreJava (18)
- 待解决 (1)
- 数据结构 (3)
- 科普 (2)
- 网站 (1)
- DataBase (8)
- Access (1)
- Asp (1)
- JSP (1)
- 操作系统 (8)
- Tech (1)
- Linux (11)
- Career (5)
- MongoDB (1)
- Embedded (1)
- JavaScript (1)
- UltraIso (1)
- Linux命令 (1)
- DesignPattern (1)
- Ruby (13)
- Vim (1)
- 自考 (2)
- Github (5)
- zrProject (1)
- Emacs (4)
- Math (3)
- Ajax (1)
- 没看懂 (1)
- HTML (1)
- Philosophy (1)
- 软件 (1)
- 面试 (1)
- 考试报名 (3)
- Regex (1)
- 日语 (1)
- 生活 (1)
最新评论
What is Thread Local?
Thread Local can be considered as a scope of access, like a request scope or session scope. It’s a thread scope. You can set any object in Thread Local and this object will be global and local to the specific thread which is accessing this object. Global and local!!? Let me explain:
- Values stored in Thread Local are global to the thread, meaning that they can be accessed from anywhere inside that thread. If a thread calls methods from several classes, then all the methods can see the Thread Local variable set by other methods (because they are executing in same thread). The value need not be passed explicitly. It’s like how you use global variables.
- Values stored in Thread Local are local to the thread, meaning that each thread will have it’s own Thread Local variable. One thread can not access/modify other thread’s Thread Local variables.
Well, that’s the concept of Thread Local. I hope you understood it (if not, please leave a comment).
When to use Thread Local?
We saw what is thread local in the above section. Now let’s talk about the use cases. i.e. when you’ll be needing something like Thread Local.
I can point out one use case where I used thread local. Consider you have a Servlet which calls some business methods. You have a requirement to generate a unique transaction id for each and every request this servlet process and you need to pass this transaction id to the business methods, for logging purpose. One solution would be passing this transaction id as a parameter to all the business methods. But this is not a good solution as the code is redundant and unnecessary.
To solve that, you can use Thread Local. You can generate a transaction id (either in servlet or better in a filter) and set it in the Thread Local. After this, what ever the business method, that this servlet calls, can access the transaction id from the thread local.
This servlet might be servicing more that one request at a time. Since each request is processed in separate thread, the transaction id will be unique to each thread (local) and will be accessible from all over the thread’s execution (global).
Got it!?
How to use Thread Local?
Java provides an ThreadLocal object using which you can set/get thread scoped variables. Below is a code example demonstrating what I’d explained above.
Lets first have the Context.java file which will hold the transactionId field.
01.
package
com.veerasundar;
02.
03.
public
class
Context {
04.
05.
private
String transactionId =
null
;
06.
07.
/* getters and setters here */
08.
09.
}
Now create the MyThreadLocal.java file which will act as a container to hold our context object.
01.
package
com.veerasundar;
02.
03.
/**
04.
* this class acts as a container to our thread local variables.
05.
* @author vsundar
06.
*
07.
*/
08.
public
class
MyThreadLocal {
09.
10.
public
static
final
ThreadLocal userThreadLocal =
new
ThreadLocal();
11.
12.
public
static
void
set(Context user) {
13.
userThreadLocal.set(user);
14.
}
15.
16.
public
static
void
unset() {
17.
userThreadLocal.remove();
18.
}
19.
20.
public
static
Context get() {
21.
return
userThreadLocal.get();
22.
}
23.
}
In the above code, you are creating a ThreadLocal object as a static field which can be used by rest of the code to set/get thread local variables.
Let’s create our main class file which will generate and set the transaction ID in thread local and then call the business method.
01.
package
com.veerasundar;
02.
03.
public
class
ThreadLocalDemo
extends
Thread {
04.
05.
public
static
void
main(String args[]) {
06.
07.
Thread threadOne =
new
ThreadLocalDemo();
08.
threadOne.start();
09.
10.
Thread threadTwo =
new
ThreadLocalDemo();
11.
threadTwo.start();
12.
}
13.
14.
@Override
15.
public
void
run() {
16.
// sample code to simulate transaction id
17.
Context context =
new
Context();
18.
context.setTransactionId(getName());
19.
20.
// set the context object in thread local to access it somewhere else
21.
MyThreadLocal.set(context);
22.
23.
/* note that we are not explicitly passing the transaction id */
24.
new
BusinessService().businessMethod();
25.
MyThreadLocal.unset();
26.
27.
}
28.
}
Finally, here’s the code for the BusinessService.java which will read from thread local and use the value.
01.
package
com.veerasundar;
02.
03.
public
class
BusinessService {
04.
05.
public
void
businessMethod() {
06.
// get the context from thread local
07.
Context context = MyThreadLocal.get();
08.
System.out.println(context.getTransactionId());
09.
}
10.
}
When you run the ThreadLocalDemo file, you’ll get the below output:
1.
Thread-0
2.
Thread-1
As you might see, even though we are not explicitly passing the transaction id, the value can be accessed from the business method and printed on the console. Adding to it, the transaction ID differs for each thread (0 and 1).
Well, that’s it. I hope I’d explained it in a simple possible way. Please let me know what do you think about this article in comments. Do leave a comment if you want to add anything to this topic.
发表评论
-
利用反射实现ORM
2012-03-28 13:37 982http://royzhou1985.iteye.com ... -
Eclipse插件安装
2012-03-28 09:29 899装载:http://gooss.org/are-two- ... -
Date & Calendar 类的使用
2012-03-27 14:19 658Java 语言的Calendar(日历),Date(日期 ... -
Java文件流 编码问题 - 读取文件时指定字符编码
2012-03-25 22:04 11529折磨了一天的问题,终于在黄昏的时候解决了,现在一吐为 ... -
打jar包
2012-02-04 17:12 743其实JAR文件的格式是ZIP ... -
JavaBean - Bound属性
2012-02-04 15:54 9964.4.3 Bound属性 Bound属性表示当该种 ... -
怎样在程序里获得一个空指针?
2012-01-28 15:56 6666.2 怎样在程序里获 ... -
制作可执行的Jar包
2012-01-22 16:35 733通常有两种,一种是制 ... -
Jni介绍
2011-10-26 19:33 587http://baike.baidu.com/view/127 ... -
获取外网IP地址
2011-10-26 18:47 897访问 http://checkip.dyndns.org/ -
this 与 getSource() 细节
2011-10-14 19:33 698一个对象实例化之后,在它的方法体中出现的this就是指自身。a ... -
static变量生存周期
2011-10-13 22:38 923标准规定static变量保证在第一次使用前初始化,但是并不保证 ... -
String 引用类型与基本类型区别
2011-10-13 22:20 806String a="A"; Stri ... -
为什么会有serialVersionUID
2011-10-13 21:17 617java文件中为什么会有s ... -
抽象类与接口的区别
2011-10-09 11:30 548首先,我们来看一下抽象类的概念,java编程思想中说“万物皆对 ... -
transient用法
2011-09-19 11:16 801Java的serialization提供了一种持久化对象实例的 ... -
例1.1 TextFileTest
2011-07-06 23:19 664package SectionIO; import java ...
相关推荐
在IT领域,线程本地存储(TLS,Thread Local Storage)是一种编程技术,它允许程序为每个线程维护独立的数据副本。这种技术在多线程环境中非常有用,因为它避免了数据竞争,提高了并发性能,同时也提供了数据隔离。...
标题“TLS_TEST.rar_TLS_Thread Local Storage”涉及到的是关于网络安全中的Transport Layer Security(TLS)协议以及在编程中的Thread Local Storage(TLS)概念。TLS是互联网上用于保护数据传输的安全标准,而...
【并发并行】_【C/C++]_【使用线程本地存储Thread Local Storage(TLS)调用复制文件接口的案例】 在多线程编程中,线程本地存储(Thread Local Storage,简称TLS)是一种用于存储线程私有数据的技术。每个线程都有...
【标题】"transmittable-thread-local" 是一个开源项目,主要关注的是线程局部变量(Thread Local)的可传递性问题。在Java编程语言中,线程局部变量是一种特殊类型的变量,它为每个线程提供独立的实例,确保了线程...
赠送jar包:transmittable-thread-local-2.12.1.jar; 赠送原API文档:transmittable-thread-local-2.12.1-javadoc.jar; 赠送源代码:transmittable-thread-local-2.12.1-sources.jar; 赠送Maven依赖信息文件:...
线程局部存储(thread-local storage, TLS)是一个使用很方便的存储线程局部数据的系统。利用TLS机制可以为进程中所有的线程关联若干个数据,各个线程通过由TLS分配的全局索引来访问与 自己关联的数据。这样,每个...
赠送jar包:transmittable-thread-local-2.12.2.jar; 赠送原API文档:transmittable-thread-local-2.12.2-javadoc.jar; 赠送源代码:transmittable-thread-local-2.12.2-sources.jar; 赠送Maven依赖信息文件:...
赠送jar包:transmittable-thread-local-2.12.1.jar; 赠送原API文档:transmittable-thread-local-2.12.1-javadoc.jar; 赠送源代码:transmittable-thread-local-2.12.1-sources.jar; 赠送Maven依赖信息文件:...
6. **线程局部存储(Thread Local Storage, TLS)** 使用`thread_local`关键字,可以在每个线程中创建独立的数据副本,避免了线程间的数据共享问题。在`Message.h`中,可能用`thread_local`为每个线程维护独立的...
- **线程局部存储(Thread Local Storage, TLS)**:`std::thread_local`关键字可以创建线程局部变量,每个线程拥有独立的副本。 - **未来(Future)和承诺(Promise)**:`std::future`和`std::promise`提供了一...
10. **线程局部存储**:线程局部存储(TLS,Thread Local Storage)允许每个线程拥有自己的变量副本,避免了线程间的数据冲突。`pthread_getspecific()`和`pthread_setspecific()`函数用于访问和设置线程局部存储。 ...
- **线程局部存储(TLS, Thread Local Storage)**:可以使用`thread_local`关键字为每个线程创建独立的存储空间。 8. **学习资源**: - `std--thread(线程)_傻月菇凉的博客-CSDN博客`和`C++11 mutex方便的自...
为了保持线程之间的独立性,Boost线程库引入了线程局部存储(TLS,Thread Local Storage)的概念。TLS允许每个线程拥有自己的数据副本,即使这些数据是在全局作用域中声明的。这种方式避免了线程之间因共享数据而...
此外,Windows还提供了线程局部存储(TLS,Thread Local Storage),允许每个线程拥有自己的变量副本,避免了多线程环境中的数据共享问题。可以使用`TlsAlloc`分配TLS索引,然后通过`TlsSetValue`和`TlsGetValue`...
1. **线程局部存储(Thread Local Storage)**:Libevent可能使用TLS来存储线程特有的数据,如事件基或配置信息,以避免在多线程环境中的冲突。 2. **回调函数的执行**:在多线程环境下,回调函数的执行需要确保...
线程局部存储(Thread Local Storage,TLS)使得每个线程可以拥有自己独立的变量副本,即使这些变量在全局或静态作用域内。`boost::thread_specific_ptr`是Boost库提供的一个工具,用于管理线程特有的指针,防止内存...
线程本地 可移植,实现可配置,... 宏THREAD_LOCAL(...)的默认实现是c ++ 11 thread_local关键字(如果支持)。 否则,将使用pthread和FLS实现。 为什么 c++11 thread_local不适用于vs2013,macOS <10> )必须具有静态
5. **线程局部存储(Thread Local Storage, TLS)** - 使用`thread_local`关键字可以声明线程局部变量,每个线程都有自己独立的一份副本,不会互相干扰。 6. **线程池** - 线程池是一种优化策略,预先创建一组...
5. **线程局部存储**:线程局部存储(Thread Local Storage,TLS)允许每个线程拥有自己的变量副本,避免了多线程环境下的数据冲突。 6. **线程池**:为管理大量线程,可以使用线程池。线程池预先创建一定数量的...
5. **线程局部存储(TLS, Thread Local Storage)** 使用`thread_local`关键字,可以声明一个变量为线程局部,每个线程拥有该变量的独立实例。 6. **线程安全** 在多线程环境下,不是所有操作都是线程安全的。...