GeeCON Prague 2014*
The moose likes Threads and Synchronization and the fly likes Regarding ThreadLocal and Volatile Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Regarding ThreadLocal and Volatile" Watch "Regarding ThreadLocal and Volatile" New topic
Author

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: 18876
    
  40

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


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
 
GeeCON Prague 2014
 
subject: Regarding ThreadLocal and Volatile