Advertisement
DulcetAirman

JMM volatile field demo

Jul 23rd, 2020
974
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.29 KB | None | 0 0
  1. package ch.claude_martin.foo;
  2.  
  3. import java.util.concurrent.ExecutorService;
  4. import java.util.concurrent.ForkJoinPool;
  5.  
  6. public class MyClass {
  7.  
  8.     static class Car {
  9.         private String owner = "N/A";
  10.  
  11.         public String getOwner() {
  12.             return this.owner;
  13.         }
  14.  
  15.         public void setOwner(String o) {
  16.             this.owner = o;
  17.         }
  18.     }
  19.  
  20.     volatile Car car = null;
  21.  
  22.     public static void main(String args[]) throws InterruptedException {
  23.         new MyClass().go();
  24.     }
  25.  
  26.     void go() throws InterruptedException {
  27.  
  28.         ExecutorService es = ForkJoinPool.commonPool();
  29.         Runnable taskA = () -> {
  30.             car = null;
  31.         };
  32.  
  33.         Runnable taskB = () -> {
  34.             car = new Car();
  35.             // we call yield() because it would be rather unlikely that the thread is
  36.             // interrupted here. You can remove it, but it will take longer.
  37.             Thread.yield();
  38.             car.setOwner("Jane");
  39.         };
  40.  
  41.         Runnable taskC = () -> {
  42.             final Car copy = car; // taskA might set this to null at any time
  43.             if (copy != null) {
  44.                 final String owner = copy.getOwner();
  45.                 if ("N/A".equals(owner)) {
  46.                     System.err.println(owner);
  47.                     System.exit(0);// Stop the VM because we got to read the initial value
  48.                 }
  49.                 // else System.out.println(owner);
  50.             }
  51.         };
  52.  
  53.         while (true) {
  54.             es.submit(taskA);
  55.             es.submit(taskB);
  56.             es.submit(taskC);
  57.         }
  58.     }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement