What is volatile in java ?

Voltile in Java with explanation and example

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.


public class VolatileExample {

public static void main(String args[]) {

new ExampleThread("Thread 1 ").start();

new ExampleThread("Thread 2 ").start();

}

}

class ExampleThread extends Thread {

private volatile int testValue;

public ExampleThread(String str){

super(str);

}

public void run() {

for (int i = 0; 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();

}

}

}

}




No comments:

Post a Comment