Please refer to the following codes.
Shared.java
class Shared
{
public volatile int i = 0;
}
CreateThread.java
class CreateThread
{
public static void main(String[] args) throws InterruptedException
{
Shared s = new Shared();
MyThread t1 = new MyThread(s);
t1.start();
while(s.i!=7)
System.out.println(s.i);
}
}
MyThread.java
class MyThread extends Thread
{
Shared s = null;
MyThread(Shared s)
{
this.s = s;
}
public void run()
{
for(int j=0; j<15; j++)
{
/* try
{
Thread.sleep(1000);
}
catch(Exception e){}*/
s.i = s.i+1;
// System.out.println("New Value of s.i "+s.i);
/* try
{
Thread.sleep(1000);
}
catch(Exception e){}*/
}
System.out.println("Thread Going to Stop");
}
}
If the new thread is not allowed to sleep, then it seems that the main thread cannot find all the values of the variable s.i. Because in this case, we are getting the following output.
0
15
15
15
..
..
..
If the new thread is allowed to sleep, then it seems that the main thread can find all the values of the variable s.i. Because in this case, we are getting the following output.
0
0
..
1
1
..
2
2
..
3
3
..
4
4
..
upto 6
From the above output, it is clear that if the new thread does not go into the sleep state, the new thread is changing the value of s.i in memory several times before the thread main gets a chance to read it.
If I change the program as:
Shared.java
class Shared
{
public /*volatile*/ boolean i = false;
}
MyThread.java
class MyThread extends Thread
{
Shared s = null;
MyThread(Shared s)
{
this.s = s;
}
public void run()
{
s.i = true;
System.out.println("New Value of s.i "+s.i);
try
{
Thread.sleep(10000);
}
catch(Exception e){}
System.out.println("Thread Going to Stop");
}
}
CreateThread.java
class CreateThread
{
public static void main(String[] args) throws InterruptedException
{
Shared s = new Shared();
MyThread t1 = new MyThread(s);
t1.start();
while(s.i==false)
System.out.println(s.i);
System.out.println(s.i+" Main Stopped");
}
}
Output:
C:\Users\gyan0\OneDrive\Desktop>java CreateThread
false
New Value of s.i true
true Main Stopped
Thread Going to Stop
It seems that the data, even though it is not volatile, is becoming immediately available to the thread.
Following are my questions.
- Does the volatile keyword guarantee the latest value to be read by a reader thread?
- What the benefits we would get if volatile keyword saves a data in memory by not saving it in CPU Register? Can you give a practical working example proving the benefits of the volatile?