Java ThreadLocal静态? [英] Java ThreadLocal static?

查看:191
本文介绍了Java ThreadLocal静态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在本地线程中设置值:

//Class A holds the static ThreadLocal variable.

    Class A{

    public static ThreadLocal<X> myThreadLocal = new ThreadLocal<X>();             
    ....
    }


//A Class B method sets value in A's static ThreadLocal variable 
    class B{
    {
         public void someBmethod(){
             X x = new X();
             A.myThreadLocal.set(x);
         }
    }


//Class C retrieves the value set in A's Thread Local variable.

    Class C {

    public void someCMethod(){
         X x = A.myThreadLocal.get();
    }
    ...
    }

Quesiton

现在假设这是一个Web应用程序,并且线程按顺序执行:B.someBMethod,C.someCMethod。

Quesiton:
Now assuming this is a web-application, and threads execute: B.someBMethod, C.someCMethod in that order.

执行B的someBMethod的多个线程将最终更新 SAME A的静态ThreadLocal变量myThreadLocal,从而击败了ThreadLocal变量的目的。 (根据文档推荐使用static for ThreadLocal。)

Multiple threads executing B's someBMethod, will end up updating the SAME A's static ThreadLocal variable myThreadLocal, thereby beating the very purpose of ThreadLocal variable. (Using static for ThreadLocal is what is recommended as per documentation.)

C的someCMethod,从ThreadLocal中检索值可能无法获得当前线程设置的值。

The C's someCMethod, while retrieving value from ThreadLocal may not get the value set by the 'current' thread.

我在这里缺少什么?

推荐答案

按照 ThreadLocal 课程的定义


此类提供线程局部变量。这些变量与正常对应的
不同,因为访问一个
的每个线程(通过其get或set方法)都有自己的,独立初始化的
变量副本。
ThreadLocal实例通常是希望将状态与线程
关联的类中的私有
静态字段(例如,用户ID或事务ID)。

This class provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread (e.g., a user ID or Transaction ID).

这意味着说2个线程 t1 & t2 执行 someBMethod()并最终设置 x1 &安培; x2 (实例 X )。现在当 t1 来执行 someCMethod()时,它获得 x1 (早先设置 本身)和 t2 获取 x2

That means say 2 threads t1 & t2 executes someBMethod() and they end up setting x1 & x2(Instances of X) respectively. Now when t1 comes and executes someCMethod() it gets x1 (which is set by itself earlier) and t2 gets x2.

换句话说,有一个静态实例 ThreadLocal 是安全的,因为在内部它当你调用 set

In other words, its safe to have a single static instance of ThreadLocal, because internally it does something like this when you invoke set

set(currentThread, value) //setting value against that particular thread

当你调用get

get(currentThread) //getting value for the thread

这篇关于Java ThreadLocal静态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆