alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

Java example source code file (CountDownLatch.java)

This example Java source code file (CountDownLatch.java) is included in the alvinalexander.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.

Learn more about this Java project at its project page.

Java - Java tags/keywords

count, countdownlatch, illegalargumentexception, illegalstateexception, interruptedexception, may, string, timeunit

The CountDownLatch.java Java example source code

/*
 * This file is a modified version of
 * http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/main/java/util/concurrent/CountDownLatch.java?revision=1.43
 * which contained the following notice:
 *
 * Written by Doug Lea with assistance from members of JCP JSR-166
 * Expert Group and released to the public domain, as explained at
 * http://creativecommons.org/publicdomain/zero/1.0/
 */

package java.util.concurrent;

/**
 * Emulation of CountDownLatch in GWT. Since GWT environment is single threaded, attempting to block
 * on the latch by calling {@link #await()} or {@link #await(long, TimeUnit)} when it is not ready
 * is considered illegal because it would lead to a deadlock. Both methods will throw {@link
 * IllegalStateException} to avoid the deadlock.
 */
public class CountDownLatch {

  private int count;

  public CountDownLatch(int count) {
    if (count < 0) {
      throw new IllegalArgumentException("count < 0");
    }
    this.count = count;
  }

  public void await() throws InterruptedException {
    if (count > 0) {
      throw new IllegalStateException("May not block. Count is " + count);
    }
  }

  public boolean await(long timeout, TimeUnit unit)
      throws InterruptedException {
    await();
    return true;
  }

  public void countDown() {
    if (count > 0) {
      count--;
    }
  }

  public long getCount() {
    return count;
  }

  public String toString() {
    return super.toString() + "[Count = " + count + "]";
  }
}

Other Java examples (source code examples)

Here is a short list of links related to this Java CountDownLatch.java source code file:

... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.