Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Regarding ThreadLocal and Volatile

 
surya.raaj prakash
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Pie
Posts: 21510
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic