Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (3.4k points)

At work today, I came across the volatile keyword in Java. Not being very familiar with it, I found this explanation:

Java theory and practice: Managing volatility

Given the detail in which that article explains the keyword in question, do you ever use it or could you ever see a case in which you could use this keyword in the correct manner?

1 Answer

0 votes
by (46k points)

Using volatile is a method (like synchronized, atomic wrapper) of making class thread safe. Thread safe means that a method or class example can be used by multiple threads at the very time without any difficulty.

Examine a simple example.

class SharedObj

{

   // Changes made to sharedVar in one thread

   // may not immediately reflect in other thread

   static int sharedVar = 6;

}

Assume that two threads are running on SharedObj. If two threads run on various processors each thread may have its local copy of the shared variable. If one thread changes its value the change might not reflect in the primary one in the main memory immediately. This depends on the reproduced policy of the cache. Now the other thread is not aware of the revised value which leads to data variance.

Note that write of standard variables without any synchronization actions, might not be noticeable to any reading thread (this behavior is called sequential consistency). Although most modern hardware stores good cache coherence, therefore, most probably the differences in one cache are reflected in other but it’s not a good method to rely on hardware to ‘fix’ a faulty application.

class SharedObj

{

   // volatile keyword here makes sure that

   // the changes made in one thread are 

   // instantly reflect in other thread

   static volatile int sharedVar = 6;

}

 

Note that volatile should not be confounded with the static modifier. static variables are class members that are distributed among all objects. There is only one copy of them in the main memory

Related questions

Browse Categories

...