• Post Reply Bookmark Topic Watch Topic
  • New Topic

Usage of Volatile keyword  RSS feed

 
Shemida Nivedha
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

I came across a doc which stated that the usage of "volatile" fields in a class maintains sequential consistency of values.
I have not used volatile much in my coding and so could you give me a brief description about the appropriate usage and uses of using it.
Also please give me hint of how out JIT compilers have implemented the volatile keywords usage.

Thanks in advance,
Shemida
 
Ankit Garg
Sheriff
Posts: 9610
37
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Volatile keyword is important because sometimes JVM caches the value of a variable for performance. In a multi-threaded system this can be a problem as a value set by one thread might not be visible to other threads for some time. If you don't want the JVM to cache the value of the variable, then you can make it volatile...
 
Stephan van Hulst
Saloon Keeper
Posts: 7928
143
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The volatile keyword simply tells the program that intermediary results of calculations on the volatile variable should not be cached.

Normally a program might leave a value in the processor register or in the memory cache or something like this, and only write it back to main memory at unknown points in time. This is fine for sequential execution, but if multiple threads try to access such a variable in memory, they might be accessing an old version of the variable, while the most current version is still in a register or in the cache.
Making a variable volatile prevents this. After every operation on it, its value gets written back to main memory. This is slower, but ensures that every thread is looking at the same value when they inspect a variable.

If a variable is edited and read by multiple threads, and access is restricted by synchronized blocks, then you don't have to worry about using volatile. When a thread enters a synchronized block, operations on that variable will be cached as they normally are, and as soon as the thread leaves the synchronized block, the final value in the cache is automatically written back to memory.

So in conclusion, you only have to use volatile if multiple threads access a variable, and the variable isn't protected by a synchronized block.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!