This tip explains the use of volatile keyword in Java. The keyword volatile (Java) is used in the multithreaded environment.
also read:
- Java Tutorials
- Java EE Tutorials
- Design Patterns Tutorials
- Java File IO Tutorials
Volatile Keyword in Local Variables in the Thread
If you are working with the multithreaded 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 using the volatile keyword, 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.
Volatile Java Example
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(); } }