Reputation: 41
I have recently started studying multithreading in core Java. I am studying a Volatile keyword. As per my understanding threads are allowed to keep the values of the variables locally. If the variables are driving any logic (e.g. loop) then the changes to the variables will not be visible to the threads and they will keep using the outdated cached values unless the variable declared as 'volatile'.
I created a small code to demonstrate this, however, my observation is different. The changes made by one thread (main thread) are very well visible to the other thread even if the shared variable 'done' is not volatile. Could anyone please help me understand this behavior
package com.test;
public class App implements Runnable {
private boolean done= true;
private static App a = new App();
public static void main( String[] args ) throws InterruptedException {
Thread t = new Thread(a);
t.start();
System.out.println("Main Thread:"+ Thread.currentThread().getName());
Thread.sleep(1);
a.done=false;
System.out.println("Value of done in main method is:"+ a.done);
}
public void run() {
while(done) {
System.out.println("Second Thread:"+ Thread.currentThread().getName());
System.out.println("Still running");
}
}
}
Output of the above code is as follows
Main Thread:main
Second Thread:Thread-0
Still running
Second Thread:Thread-0
Still running
Second Thread:Thread-0
Still running
Second Thread:Thread-0
Still running
Second Thread:Thread-0
Still running
Second Thread:Thread-0
Still running
Value of done in main method is:false
Upvotes: 1
Views: 108
Reputation: 1695
The keyword volatile
guarantees the behavior you described. The value of a volatile
field is visible to all readers after a write
operation. This means that no cached values are used.
If you are not using the volatile
keyword this does not automatically mean though that you are always using old, cached variables. It's just the possibility that this could happen.
Takeaway:
You use the volatile
keyword to guarantee memory visibility. It does not mean that not using it will break your code as soon as you use multithreading.
Also note that volatile
does not guarantee atomic interaction with your variable. This means that a volatile
field is not automatically thread safe regarding race conditions and other potential trouble.
Upvotes: 3