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
java
@Component @Converter public class EncryptedStringConverter implements AttributeConverter<String, String> {
Transparent column encryption in Spring & JPA
encryption
aes-gcm
jpa-converter
Advanced
10 steps
java
package com.acme.billing.config; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.ConfigurationProperties;
Feature-flagged beans with Spring @ConditionalOnProperty
feature-flags
conditional-beans
strategy-pattern
Intermediate
5 steps
go
func (w *Watcher) resetDebounce(d time.Duration) { if !w.timer.Stop() { select { case <-w.timer.C:
Debouncing a stream of events in Go
debounce
timers
channels
Advanced
7 steps
java
public static Map<String, String> parseCookieHeader(String header) { Map<String, String> cookies = new LinkedHashMap<>(); if (header == null || header.isBlank()) { return cookies;
Parsing an HTTP Cookie header in Java
string-parsing
http
url-decoding
Intermediate
6 steps
python
import secrets from django.contrib.auth import authenticate, login from django.core.cache import cache
Two-factor login with OTP in Django
two-factor-auth
one-time-passwords
caching
Intermediate
9 steps
rust
use std::collections::VecDeque; use std::sync::{Arc, Condvar, Mutex}; use std::time::{Duration, Instant};
Building a counting semaphore in Rust
concurrency
synchronization
condition-variable
Advanced
9 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.