Skip to content

Instantly share code, notes, and snippets.

@arunlakshman
Created August 6, 2017 07:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arunlakshman/7a7333f8871ce12a0ea1863216df24b1 to your computer and use it in GitHub Desktop.
Save arunlakshman/7a7333f8871ce12a0ea1863216df24b1 to your computer and use it in GitHub Desktop.
Java Volatile Keyword
public class VolatileTest {
private static final int MAX_TASK_COUNT = 5;
private static volatile int tasks = 0;
public static void main(String[] args) {
new Employee().start();
new Manager().start();
}
static class Employee extends Thread {
@Override
public void run() {
int local_value = tasks;
while (local_value < MAX_TASK_COUNT) {
if (local_value != tasks) {
System.out.println("Got Change for tasks : " + tasks);
local_value = tasks;
}
}
}
}
static class Manager extends Thread {
@Override
public void run() {
int local_value = tasks;
while (tasks < MAX_TASK_COUNT) {
System.out.println("Incrementing tasks to " + (local_value + 1));
tasks = ++local_value;
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment