Created
January 22, 2023 07:02
-
-
Save vishalratna-microsoft/cc8fe9a279fce48172bdd72e0ba1c6de to your computer and use it in GitHub Desktop.
Demonstrate produce-consumer problem using volatile
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class PCExample { | |
private volatile boolean shouldProduce = true; // Make this non-volatile, it will not work. | |
private int value = -1; // As we write the value before a write to volatile, this does not need to be volatile. All values | |
// will be flushed to main m/m along with volatile. Case of "happens before" guarantee. | |
public void startProducer() { | |
Runnable producer = () -> { | |
for (int i = 0; i < 10; i++) { | |
while (!shouldProduce) { } | |
System.out.println("Produced: " + i); | |
try { | |
Thread.sleep(500); | |
} catch (InterruptedException e) { | |
throw new RuntimeException(e); | |
} | |
if (value == -1) { | |
value = i; | |
} | |
shouldProduce = false; | |
} | |
}; | |
new Thread(producer).start(); | |
} | |
public void startConsumer() { | |
Runnable consumer = () -> { | |
for (int i = 0; i < 10; i++) { | |
while (shouldProduce) { } | |
System.out.println("Consumed: " + value); | |
try { | |
Thread.sleep(500); | |
} catch (InterruptedException e) { | |
throw new RuntimeException(e); | |
} | |
value = -1; | |
shouldProduce = true; | |
} | |
}; | |
new Thread(consumer).start(); | |
} | |
public void start() { | |
startProducer(); | |
startConsumer(); | |
} | |
} | |
/** | |
Driver code | |
PCExample x = new PCExample(); | |
x.start(); | |
**/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment