Java Volatile

If you are working with the multi-threaded programming, the volatile keyword will be more useful. When multiple threads using the same variable, each thread will have its own copy of the local cache for that variable. So, when it’s updating the value, it is actually updated in the local cache not in the main variable memory. The other thread which is using the same variable doesn’t know anything about the values changed by the another thread. To avoid this problem, if you declare a variable as volatile, then it will not be stored in the local cache. Whenever thread are updating the values, it is updated to the main memory. So, other threads can access the updated value.

package javabeat.samples;

class ExampleThread extends Thread {
private volatile int testValue;
public ExampleThread(String str){
super(str);
}
public void run() {
for (int i = 0; i < 3; i++) {
try {
System.out.println(getName() + ” : “+i);
if (getName().equals(“Thread 1 “))
{
testValue = 10;
}
if (getName().equals(“Thread 2 “))
{
System.out.println( “Test Value : ” + testValue);
}
Thread.sleep(1000);
} catch (InterruptedException exception) {
exception.printStackTrace();
}
}
}
}
public class VolatileExample {
public static void main(String args[]) {
new ExampleThread(“Thread 1 “).start();
new ExampleThread(“Thread 2 “).start();
}
}

 

more info:

 

Volatile… A volatile modifier is mainly used in mutiple threads. Java allows threads can keep private working copies of the shared variables(caches).These working copies need be updated with the master copies in the main memory.

But possible of data get messed up. To avoid this data corruption use volatile modifier or synchronized .volatile means everything done in the main memory only not in the private working copies (caches).( Volatile primitives cannot be cached ).

So volatile guarantes that any thread will read most recently written value.Because they all in the main memory not in the cache…Also volatile fields can be slower than non volatile.Because they are in main memory not in the cache.But volatile is useful to avoid concurrency problem.
Post a comment or leave a trackback: Trackback URL.

Leave a comment