为什么Java ThreadLocal变量应该是静态的 [英] Why should Java ThreadLocal variables be static
问题描述
我在这里阅读ThreadDocal的JavaDoc
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ThreadLocal.html
并且它表示
ThreadLocal实例通常是希望将状态与线程关联的类中的私有静态字段(例如,用户ID或事务ID)。 p>
但是我的问题是他们为什么选择让它静态(通常) - 它使得每个线程状态但是字段是静态的有点混乱?
因为如果它是一个实例级别字段,那么它实际上是每个线程 - 每个实例,而不仅仅是一个保证的每线程。这通常不是您正在寻找的语义。
通常它会保存类似于用户对话,Web请求等对象的对象。您不希望它们也被子范围化为类的实例。$
一个Web请求=>一个持久性会话。
没有一个Web请求=>每个对象一个持久性会话。
I was reading the JavaDoc for Threadlocal here
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ThreadLocal.html
and it says "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). "
But my question is why did they choose to make it static (typically) - it makes things a bit confusing to have "per thread" state but the fields are static?
Because if it were an instance level field, then it would actually be "Per Thread - Per Instance", not just a guaranteed "Per Thread." That isn't normally the semantic you're looking for.
Usually it's holding something like objects that are scoped to a User Conversation, Web Request, etc. You don't want them also sub-scoped to the instance of the class.
One web request => one Persistence session.
Not one web request => one persistence session per object.
这篇关于为什么Java ThreadLocal变量应该是静态的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!