Skip to content

Instantly share code, notes, and snippets.

@er-abhishek-luthra
Created September 5, 2020 13:57
Show Gist options
  • Save er-abhishek-luthra/54d1cc84a3927bbbd65be323d4ceca9d to your computer and use it in GitHub Desktop.
Save er-abhishek-luthra/54d1cc84a3927bbbd65be323d4ceca9d to your computer and use it in GitHub Desktop.
Practical explanation to volatile keyword -
public class VisibilityDemonstration {
private static int sCount = 0;
public static void main(String[] args) {
new Consumer().start();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
return;
}
new Producer().start();
}
static class Consumer extends Thread {
@Override
public void run() {
int localValue = -1;
while (true) {
if (localValue != sCount) {
System.out.println("Consumer: detected count change " + sCount);
localValue = sCount;
}
if (sCount >= 5) {
break;
}
}
System.out.println("Consumer: terminating");
}
}
static class Producer extends Thread {
@Override
public void run() {
while (sCount < 5) {
int localValue = sCount;
localValue++;
System.out.println("Producer: incrementing count to " + localValue);
sCount = localValue;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
return;
}
}
System.out.println("Producer: terminating");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment