Synchronization and locks · Topic 7 of 8
CountDownLatch and Semaphore
Definition​
A CountDownLatch makes a thread wait until other threads have finished a set number of steps. A Semaphore limits how many threads may use something at the same time, such as 3 database connections.
Example code​
Wait for three workers, and allow only two at a time
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;
class Demo {
public static void main(String[] args) throws InterruptedException {
CountDownLatch done = new CountDownLatch(3);
Semaphore permits = new Semaphore(2); // at most 2 at a time
AtomicInteger running = new AtomicInteger();
AtomicInteger maxRunning = new AtomicInteger();
for (int i = 0; i < 3; i++) {
new Thread(() -> {
try {
permits.acquire();
int now = running.incrementAndGet();
maxRunning.accumulateAndGet(now, Math::max);
Thread.sleep(100);
running.decrementAndGet();
permits.release();
} catch (InterruptedException ignored) { }
done.countDown(); // one step finished
}).start();
}
done.await(); // waits until the count reaches zero
System.out.println("all workers finished, at most " + maxRunning.get() + " ran together");
}
}
// Output:
// all workers finished, at most 2 ran together
Finished this page? Track your progress (saved only in your browser).