Wednesday, October 30, 2013

Regarding ThreadLocal and Volatile

surya.raaj prakash
Ranch Hand

Joined: Oct 30, 2009
Posts: 76 
Hi Friends,
can you explain to me what is difference between ThreadLocal and Volatile?and when to use ThreadLocal class and Volatile?
Actually I'm confusing with these two concepts.
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 17379 
    
  31

surya.raaj prakash wrote:can you explain to me what is difference between ThreadLocal and Volatile?and when to use ThreadLocal class and Volatile?
Actually I'm confusing with these two concepts.


They are not really related. The ThreadLocal class is a class that stores a variable in the Thread object of the current running thread, hence, while each thread can share the same ThreadLocal instance, they are not really sharing the underlying variable at all.

The volatile keyword tells the compiler that the variable is shared, and likely shared without synchronization (or just treat it as such)... Caching of the variable in registers will not be allowed (reads direct from memory, writes go straight to memory), certain code motion optimization will not be allowed, and in the case of long and double, the JVM will make sure that read and writes are atomic, even if the underlying hardware don't support 64 bit atomic operations.

Henry

No comments: