Commit 6fa08a97 authored by Trisha Gee's avatar Trisha Gee
Browse files

[Ch15] Adding a latch example to the predictable run order, and a very crude performance test.

parent af60d89b
Loading
Loading
Loading
Loading
+27 −0
Changes for src/main/java/ch15/PredictableRunOrder.java: 27 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -4,9 +4,12 @@ import java.util.concurrent.*;

public class PredictableRunOrder {
  public static void main(String[] args) throws InterruptedException {
    long startTime = System.currentTimeMillis();
    for (int i = 0; i < 100; i++) {
      PredictableSleep.main(args);
    }
    long endTime = System.currentTimeMillis();
    System.out.println(endTime-startTime);
  }
}

@@ -16,6 +19,7 @@ class PredictableSleep {
    executor.execute(() -> sleepThenPrint());
    System.out.println("back in main");
    executor.shutdown();
    executor.awaitTermination(2, TimeUnit.SECONDS);
  }

  private static void sleepThenPrint() {
@@ -34,6 +38,7 @@ class SleepWithTimeUnit {
    executor.execute(() -> sleepThenPrint());
    System.out.println("back in main");
    executor.shutdown();
    executor.awaitTermination(2, TimeUnit.SECONDS);
  }

  private static void sleepThenPrint() {
@@ -45,3 +50,25 @@ class SleepWithTimeUnit {
    System.out.println("top o’ the stack");
  }
}

class PredictableLatch {
  public static void main (String[] args) throws InterruptedException {
    ExecutorService executor = Executors.newSingleThreadExecutor();
    CountDownLatch latch = new CountDownLatch(1);
    executor.execute(() -> waitForLatchThenPrint(latch));
    System.out.println("back in main");
    latch.countDown();
    executor.shutdown();
    executor.awaitTermination(2, TimeUnit.SECONDS);
  }

  private static void waitForLatchThenPrint(CountDownLatch latch) {
    try {
      latch.await();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    System.out.println("top o’ the stack");
  }
}