简体   繁体   English

Java中真正的ThreadLocal用法

[英]Real ThreadLocal usage in Java

Just began studying Java ThreadLocal type. 刚开始研究Java ThreadLocal类型。 I could understand those typical examples of it, like defining a class, who has an instance field that is declared to be ThreadLocal; 我可以理解这些典型的示例,例如定义一个类,该类具有一个声明为ThreadLocal的实例字段。 then after creation of a object of this class, we pass this object to, say like three independent threads, they will each have their own copy of this shared object. 然后,在创建此类的对象之后,我们将该对象传递给,例如,就像三个独立的线程一样,它们将各自拥有该共享对象的副本。

My question here may be very stupid, please pardon, why don't we just create as many objects as how many threads there are, so it will (maybe) achieve the same result? 我在这里的问题可能很愚蠢,请原谅,为什么我们不仅仅创建与有多少个线程一样多的对象,那么它(可能)会达到相同的结果?

I have read the Hibernate code about using the ThreadLocal: 我已经阅读了有关使用ThreadLocal的Hibernate代码:

private static final ThreadLocal threadSession = new ThreadLocal();  

public static Session getSession() throws InfrastructureException 
{  
   Session s = (Session) threadSession.get();  
   try 
   {  
    if (s == null) {  
        s = getSessionFactory().openSession();  
        threadSession.set(s);  
       }  
   }
   catch (HibernateException ex) 
   {  
    throw new InfrastructureException(ex);  
   }    
    return s;  
} 

My possible guess is, firstly, we may not be able to predict how many threads there are going to be; 我可能的猜测是,首先,我们可能无法预测会有多少个线程。 secondly, suppose many threads will be created, then creating an object for each of them is very costly? 其次,假设将创建许多线程,那么为每个线程创建一个对象会非常昂贵吗?

Please give me some guidance here, experts :) 请给我一些指导,专家:)

Why don't we just create as many objects as how many threads there are, so it will (maybe) achieve the same result? 为什么我们不创建与拥有多少线程一样多的对象,这样(也许)会达到相同的结果?

This would require knowledge of how many threads there are. 这将需要知道有多少个线程。 More importantly, it requires that either we give an object enough information to know what thread it is on so that it can retrieve its thread-local data, or we manage the thread-local stuff at a higher level and pass it down to the objects. 更重要的是,它要求我们为对象提供足够的信息以了解其所在的线程,以便它可以检索其本地线程数据,或者我们需要在更高级别上管理本地线程的内容并将其传递给对象。 ThreadLocal lets us accomplish this in a completely self-contained way and simplifies object interfaces and management of thread-local data. ThreadLocal让我们以完全独立的方式完成此任务,并简化了对象接口和线程本地数据的管理。

ThreadLocal is a good tool that takes care of all of the dirty work for us. ThreadLocal是一个很好的工具,可以为我们处理所有肮脏的工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM