daily pastebin goal
7%
SHARE
TWEET

Untitled

a guest Jan 24th, 2019 65 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. ExecutorService executor = Executors.newFixedThreadPool(5);
  2.     double[] arr = new double[5];
  3.     for (int i=0; i<5; ++i) {
  4.         arr[i] = 1 + Math.random();
  5.     }
  6.     for (int i=0; i<5; ++i) {
  7.         final int j=i;
  8.         executor.submit(() -> System.out.println(String.format("arr[%s]=%s", j, arr[j])));
  9.     }
  10.    
  11. for (int i=0; i<5; ++i) {
  12.         arr[i] = 1 + Math.random();
  13.     }
  14.     final double[] arr2 = arr;  //<---- safe publication?
  15.     for (int i=0; i<5; ++i) {
  16.         final int j=i;
  17.         executor.submit(() -> System.out.println(String.format("arr[%s]=%s", j, arr2[j])));
  18.     }
  19.    
  20. CountDownLatch latch = new CountDownLatch(1); //1 = the number of writing threads
  21.     for (int i=0; i<5; ++i) {
  22.         arr[i] = Math.random();
  23.     }
  24.     latch.countDown();    //<- writing is done
  25.     for (int i=0; i<5; ++i) {
  26.         final int j=i;
  27.         executor.submit(() -> {
  28.             try {latch.await();} catch (InterruptedException e) {...} //happens-before(writings, reading) guarantee?
  29.             System.out.println(String.format("arr[%s]=%s", j, arr[j]));
  30.         });
  31.     }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top