I have created a small program to understand Java Volatile keyword:
public class MultiThreadedCounter implements Runnable {
private volatile int counter = 0;
public void run() {
increment();
decrement();
}
private void decrement() {
counter = counter - 5;
System.out.println("dec = " + counter);
}
private void increment() {
counter = counter + 5;
System.out.println("inc = " + counter);
}
public static void main(String[] args) throws InterruptedException {
MultiThreadedCounter m = new MultiThreadedCounter();
Thread[] t = new Thread[100];
int count = 0;
while (true) {
if (count >= 100) {
break;
}
Thread t1 = new Thread(m);
t[count] = t1;
count++;
}
for (int i = 0; i < t.length; i++) {
t[i].start();
}
}
}
Now in this program, I am seeing different set of results when I run the program multiple times.
Then I tried removing the volatile
keyword for counter
variable and observed similar results. i.e I am seeing different results when I run the program many times.
How Volatile
helps in this program? When we need to use this keyword, I have gone through some material ans SO posts but I am not getting clear picture of the usage of this keyword.