• Post Reply Bookmark Topic Watch Topic
  • New Topic

Volatile variable usecase  RSS feed

 
Ranch Hand
Posts: 116
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is the exact use case where we shod use volatile and where we should avoid using it?
 
Ranch Hand
Posts: 83
10
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You don't need to worry about volatile unless you are doing multithreading.

To increase performance in Java, when setting a variable (say an int), the new value will not be written into memory yet because writing that is costly. Instead, it will be cached so it is easier to read/write again, until it is later written to memory. In multithreading code, this is a problem because the cache is local to the thread. This means that one thread can set a value for an int, then another can read that int and get an old value.

So, volatile tells the jvm to never cache it. This means that any read/write operation is thread-safe on a volatile data type (note that incrementing is still not safe).

Use volatile in multithreaded code if multiple threads access data that can change.
Do not use volatile.. any other time.
 
Vaibhav Gargs
Ranch Hand
Posts: 116
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Zachary!

Zachary Griggs wrote:

Use volatile in multithreaded code if multiple threads access data that can change.
Do not use volatile.. any other time.


Can you please explain both the conditions giving some sample code.
 
Zachary Griggs
Ranch Hand
Posts: 83
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Realistically, it's only used in some very specific circumstances.
Demo is from here with slight modifications: https://dzone.com/articles/java-volatile-keyword-0

Code is supposed to increment an integer and report when that integer is incremented. Try it with and without the volatile keyword on MY_INT and see what happens.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!