Javatpoint Logo

91-9990449935

 0120-4256464


What is volatile keyword in java?

By: sanjay.mscit7@gmail.com On: Sat Jun 18 12:49:58 IST 2016     0 0 0  0
i have read many reference book but i cant understand volatile keyword properly. so i need proper guide about that keyword0
core java  x  220Tags

 
volatile keyword in Java is used as an indicator to Java compiler and Thread that do not cache value of this variable and always read it from main memory. So if you want to share any variable in which read and write operation is atomic by implementation e.g. read and write in an int or a boolean variable then you can declare them as volatile variable.

after Java 5 write to any volatile variable happens before any read into the volatile variable.
By the way use of volatile keyword also prevents compiler or JVM from the reordering of code or moving away them from synchronization barrier.
example
public class VolatileData
{
private volatile int counter = 0;
public int getCounter()
{
return counter;

}
public void increaseCounter()
{

++counter;
}
}

public class VolatileThread extends Thread {
private final VolatileData data;

public VolatileThread(VolatileData data) {
this.data = data;
}


public void run() {
int oldValue = data.getCounter();
System.out.println("[Thread " + Thread.currentThread().getId()
+ "]: Old value = " + oldValue);

data.increaseCounter();

int newValue = data.getCounter();
System.out.println("[Thread " + Thread.currentThread().getId()
+ "]: New value = " + newValue);
}
}


public class VolatileMain {

private final static int TOTAL_THREADS = 2;

public static void main(String[] args) throws InterruptedException {
VolatileData volatileData = new VolatileData();

Thread[] threads = new Thread[TOTAL_THREADS];
for(int i = 0; i < TOTAL_THREADS; ++i)
threads[i] = new VolatileThread(volatileData);


for(int i = 0; i < TOTAL_THREADS; ++i)
threads[i].start();

for(int i = 0; i < TOTAL_THREADS; ++i)
threads[i].join();
}
}


// if any query related to volatile then mail me my id is tiwaripawan388@gmail.com ///



0

By: tiwaripawan388@gmail.com On: Sat Jun 18 22:13:48 IST 2016 0 0 0 0
Are You Satisfied :0Yes0No


PLEASE REPLY

Please login first to post reply. Login please!