Code example for CountDownLatch

0
 
/** 
 * A locally-originated ping. 
 */ 
public final class Ping { 
  private final CountDownLatch latch = new CountDownLatch(1);
  private long sent = -1;
  private long received = -1;
 
  Ping() { 
  } 
 
  void send() { 
    if (sent != -1) throw new IllegalStateException();
    sent = System.nanoTime();
  } 
 
  void receive() { 
    if (received != -1 || sent == -1) throw new IllegalStateException();
    received = System.nanoTime();
    latch.countDown();