`

Thread Local

阅读更多

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.

分享到:
评论

相关推荐

    tls.rar_TLS_Thread Local Storage_thread local

    在IT领域,线程本地存储(TLS,Thread Local Storage)是一种编程技术,它允许程序为每个线程维护独立的数据副本。这种技术在多线程环境中非常有用,因为它避免了数据竞争,提高了并发性能,同时也提供了数据隔离。...

    TLS_TEST.rar_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)调用复制文件接口的案例]

    【并发并行】_【C/C++]_【使用线程本地存储Thread Local Storage(TLS)调用复制文件接口的案例】 在多线程编程中,线程本地存储(Thread Local Storage,简称TLS)是一种用于存储线程私有数据的技术。每个线程都有...

    transmittable-thread-local,

    【标题】"transmittable-thread-local" 是一个开源项目,主要关注的是线程局部变量(Thread Local)的可传递性问题。在Java编程语言中,线程局部变量是一种特殊类型的变量,它为每个线程提供独立的实例,确保了线程...

    transmittable-thread-local-2.12.1-API文档-中文版.zip

    赠送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依赖信息文件:...

    TLS.rar_Thread Local Storage

    线程局部存储(thread-local storage, TLS)是一个使用很方便的存储线程局部数据的系统。利用TLS机制可以为进程中所有的线程关联若干个数据,各个线程通过由TLS分配的全局索引来访问与 自己关联的数据。这样,每个...

    transmittable-thread-local-2.12.2-API文档-中文版.zip

    赠送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依赖信息文件:...

    transmittable-thread-local-2.12.1-API文档-中英对照版.zip

    赠送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依赖信息文件:...

    c++ thread

    6. **线程局部存储(Thread Local Storage, TLS)** 使用`thread_local`关键字,可以在每个线程中创建独立的数据副本,避免了线程间的数据共享问题。在`Message.h`中,可能用`thread_local`为每个线程维护独立的...

    C++_thread.zip

    - **线程局部存储(Thread Local Storage, TLS)**:`std::thread_local`关键字可以创建线程局部变量,每个线程拥有独立的副本。 - **未来(Future)和承诺(Promise)**:`std::future`和`std::promise`提供了一...

    linux-thread.rar_linux multi thread_linux thread_thread_thread l

    10. **线程局部存储**:线程局部存储(TLS,Thread Local Storage)允许每个线程拥有自己的变量副本,避免了线程间的数据冲突。`pthread_getspecific()`和`pthread_setspecific()`函数用于访问和设置线程局部存储。 ...

    c++ std thread的用法教程

    - **线程局部存储(TLS, Thread Local Storage)**:可以使用`thread_local`关键字为每个线程创建独立的存储空间。 8. **学习资源**: - `std--thread(线程)_傻月菇凉的博客-CSDN博客`和`C++11 mutex方便的自...

    C++ Boost Thread 编程指南

    为了保持线程之间的独立性,Boost线程库引入了线程局部存储(TLS,Thread Local Storage)的概念。TLS允许每个线程拥有自己的数据副本,即使这些数据是在全局作用域中声明的。这种方式避免了线程之间因共享数据而...

    class_thread.zip_window thread_windows多线程源码

    此外,Windows还提供了线程局部存储(TLS,Thread Local Storage),允许每个线程拥有自己的变量副本,避免了多线程环境中的数据共享问题。可以使用`TlsAlloc`分配TLS索引,然后通过`TlsSetValue`和`TlsGetValue`...

    libevent-thread-20140224-1.7z

    1. **线程局部存储(Thread Local Storage)**:Libevent可能使用TLS来存储线程特有的数据,如事件基或配置信息,以避免在多线程环境中的冲突。 2. **回调函数的执行**:在多线程环境下,回调函数的执行需要确保...

    C++_Boost_Thread_编程指南

    线程局部存储(Thread Local Storage,TLS)使得每个线程可以拥有自己独立的变量副本,即使这些变量在全局或静态作用域内。`boost::thread_specific_ptr`是Boost库提供的一个工具,用于管理线程特有的指针,防止内存...

    ThreadLocal:可移植和实现可配置的c ++ 11,例如线程本地

    线程本地 可移植,实现可配置,... 宏THREAD_LOCAL(...)的默认实现是c ++ 11 thread_local关键字(如果支持)。 否则,将使用pthread和FLS实现。 为什么 c++11 thread_local不适用于vs2013,macOS <10> )必须具有静态

    C++ 线程学习,thread常用操作

    5. **线程局部存储(Thread Local Storage, TLS)** - 使用`thread_local`关键字可以声明线程局部变量,每个线程都有自己独立的一份副本,不会互相干扰。 6. **线程池** - 线程池是一种优化策略,预先创建一组...

    thread_thread_

    5. **线程局部存储**:线程局部存储(Thread Local Storage,TLS)允许每个线程拥有自己的变量副本,避免了多线程环境下的数据冲突。 6. **线程池**:为管理大量线程,可以使用线程池。线程池预先创建一定数量的...

    thread.rar

    5. **线程局部存储(TLS, Thread Local Storage)** 使用`thread_local`关键字,可以声明一个变量为线程局部,每个线程拥有该变量的独立实例。 6. **线程安全** 在多线程环境下,不是所有操作都是线程安全的。...

Global site tag (gtag.js) - Google Analytics