简体   繁体   中英

Real ThreadLocal usage in Java

Just began studying Java ThreadLocal type. I could understand those typical examples of it, like defining a class, who has an instance field that is declared to be 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:

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 is a good tool that takes care of all of the dirty work for us.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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