java
27 lines · 6 steps
Bounding concurrency with a Semaphore in Java
A Semaphore caps how many tasks run at once and rejects callers that wait too long.
Explained by
highlit
1public class RequestThrottler {
2
3 private final Semaphore permits;
4 private final long acquireTimeoutMillis;
5
6 public RequestThrottler(int maxInFlight, long acquireTimeoutMillis) {
7 this.permits = new Semaphore(maxInFlight, true);
8 this.acquireTimeoutMillis = acquireTimeoutMillis;
9 }
10
11 public <T> T execute(Callable<T> task) throws Exception {
12 boolean acquired = permits.tryAcquire(acquireTimeoutMillis, TimeUnit.MILLISECONDS);
13 if (!acquired) {
14 throw new RejectedExecutionException(
15 "Request rejected: " + permits.getQueueLength() + " callers waiting, no permits available");
16 }
17 try {
18 return task.call();
19 } finally {
20 permits.release();
21 }
22 }
23
24 public int availablePermits() {
25 return permits.availablePermits();
26 }
27}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A fair Semaphore is a clean primitive for capping in-flight work without spinning up thread pools.
- 2Bounded acquire timeouts turn silent queuing into fast, explicit rejection under overload.
- 3Releasing in a finally block guarantees permits return even when the task throws.
Related explainers
go
package metrics import ( "sync"
A thread-safe sliding-window average in Go
concurrency
sliding-window
running-average
Intermediate
8 steps
java
public record AppConfig( String host, int port, String databaseUrl,
Loading typed config from env vars in Java
records
configuration
environment-variables
Intermediate
6 steps
python
import time import threading from flask import Flask, request, jsonify, g
A token-bucket rate limiter in Flask
rate-limiting
token-bucket
middleware
Intermediate
7 steps
go
package middleware import ( "context"
Per-tenant daily rate limiting in Gin
rate-limiting
middleware
redis
Intermediate
8 steps
java
public List<DailySample> backfillMissingDates(List<DailySample> samples, double fillValue) { if (samples.isEmpty()) { return List.of(); }
Backfilling gaps in a daily time series in Java
streams
time-series
treemap
Intermediate
5 steps
ruby
class Document < ApplicationRecord class StaleObjectError < StandardError def initialize(id) super("Document ##{id} was modified by another process")
Optimistic locking with retries in Rails
optimistic-locking
concurrency
transactions
Advanced
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/bounding-concurrency-with-a-semaphore-in-java-explained-java-19ae/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.