Advertisement
Guest User

Untitled

a guest
Apr 10th, 2016
347
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.39 KB | None | 0 0
  1. public class Playground {
  2.  
  3.     static class Safe {
  4.         private final int value;
  5.  
  6.         public Safe(int value) {
  7.             this.value = value;
  8.         }
  9.     }
  10.  
  11.     static class IsItSafe {
  12.         private /* volatile */ Safe safe;
  13.  
  14.         public int get(){
  15.             return safe.value;
  16.         }
  17.  
  18.         public void set(int value) {
  19.             safe = new Safe(value);
  20.         }
  21.     }
  22.  
  23.     private static /* volatile */ IsItSafe sharedData = new IsItSafe();
  24.  
  25.     public static void main(String[] args) {
  26.  
  27.         new Thread(new Runnable() {
  28.             @Override
  29.             public void run() {
  30.                 int counter = 0;
  31.                 while (counter < Integer.MAX_VALUE) {
  32.                     counter++;
  33.                     sharedData.set(counter);
  34.                 }
  35.                 System.out.printf("[T1] Shared data visible here is %d\n", sharedData.get());
  36.             }
  37.         }).start();
  38.  
  39.         new Thread(new Runnable() {
  40.             @Override
  41.             public void run() {
  42.                 int locallyRead = Integer.MIN_VALUE;
  43.                 while (sharedData.get() < Integer.MAX_VALUE) {
  44.                     locallyRead = sharedData.get();
  45.                 }
  46.                 System.out.printf("[T2] Last read value here is %d\n[T2] Shared data visible here is %d\n", locallyRead, sharedData.get());
  47.             }
  48.         }).start();
  49.  
  50.     }
  51.  
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement