Skip to content

Checking your reading list…

Retry

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

Thread Pool Deep Dive: Worker AQS, Dynamic Tuning, Rejection & Load Testing

This article analyzes three production thread pool incidents, explains Worker AQS internals, details dynamic parameter tuning semantics, queue sizing and rejection strategies, monitoring metrics, and a five-step tuning loop with practical code templates for dynamic scaling, timed adjustments, custom rejection handlers, and observability.

This article advances beyond basic thread pool creation to address the core production challenge: parameters that fit load at creation time become stale as traffic fluctuates. It dissects three real incidents, reveals the Worker's AQS-based internals, defines precise runtime semantics for dynamic tuning, treats queue capacity as a buffered budget, and establishes a closed-loop observability and tuning process.

Three Production Incidents

Incident 1: Unbounded Queue OOM. An order system used Executors.newFixedThreadPool(32) backed by a LinkedBlockingQueue (default capacity ~2.1 billion). Daily QPS 200 caused near-zero queueing; a promotion tripled QPS to 600. The 32 threads couldn't keep up, 80,000 tasks piled up, each holding a large JSON object. Heap exhausted in 40 minutes, Full GC couldn't reclaim, service OOM restarted, queued tasks lost. Root cause: unbounded queue shifts the capacity limit to OOM. Fix: ArrayBlockingQueue(2000) + custom rejection handler persisting to DB + queue depth alerting.

Incident 2: Blind Doubling of Core Threads. High latency prompted doubling corePoolSize from 64 to 128 on a 32-core machine. Throughput didn't improve; CPU rose from 45% to 70%, sys CPU doubled, P99 latency increased 30%. The workload was CPU-intensive; the formula N = cores × (1 + wait/compute) requires measured wait/compute ratio, not guesswork. Adding threads only increased context-switch overhead.

Incident 3: Parameter Change Without Effect. A config-center listener called setCorePoolSize(8) to shrink, but active threads didn't drop for a week. Two reasons: shrink only interrupts idle workers (long-running queries kept threads busy), and queued tasks continue consuming at the old rate. Tuning changes future scheduling, not existing backlog. Fix: post-change read-back verification + drain backlog + change audit trail.

Worker's AQS Perspective

Each worker is a Worker inner class extending AbstractQueuedSynchronizer and implementing Runnable. It holds its Thread and an optional firstTask. The AQS state acts as a non-reentrant exclusive lock: state 0 = idle, state 1 = running task. runWorker locks before each task, unlocks after. This lock enables graceful shutdown: shutdown() calls interruptIdleWorkers which tries to acquire the lock; success means idle (state 0) and the thread is interrupted; failure means busy and the thread is left alone. setState(-1) in the constructor prevents premature interruption before runWorker starts.

Figure 1: Three tuning incidents, four untold topics from part 01, and this article's roadmap
Figure 1: Three tuning incidents, four untold topics from part 01, and this article's roadmap

Thread lifecycle is governed by getTask. Core threads ( workerCount ≤ corePoolSize) block indefinitely on workQueue.take(); non-core threads use poll(keepAliveTime) and exit on timeout. allowCoreThreadTimeOut(true) makes all threads use timed poll, allowing the pool to shrink to zero during low traffic. processWorkerExit replaces a worker if the pool is still running and worker count is below core, enforcing core pool size conservation.

CTL high 3 bits encode lifecycle: RUNNING (accept tasks, process queue), SHUTDOWN (reject new, drain queue), STOP (reject new, ignore queue, interrupt all), TIDYING/TERMINATED (final). getTask returns null only when SHUTDOWN and queue empty, implementing graceful drain.

Dynamic Tuning: Three Setters and Precise "Effect" Definition

All three core parameters have runtime setters: setCorePoolSize: increase or decrease. Increase does not pre-create threads (waits for new tasks); decrease calls interruptIdleWorkers to let idle threads exit naturally. setMaximumPoolSize: increase or decrease. Decrease retains over-limit threads until they fail to fetch tasks and exit. allowCoreThreadTimeOut: toggles the timed flag in getTask immediately.

These are ordinary synchronized methods — thread pools are inherently dynamic; static parameters are just a usage habit.

"Effect" must be precisely defined: new tasks follow new parameters; existing queued tasks and running threads continue unchanged. Three corollaries:

Scale-up only adds threads when new tasks arrive (or via prestartAllCoreThreads).

Scale-down only stops idle threads; busy threads finish first.

Queue backlog is independent; tuning doesn't clear it — requires drain or natural consumption.

The cognitive trap: "parameter changed, so behavior changes instantly" — parameters are rules, not immediate commands.

Figure 2: Worker AQS perspective, worker lifecycle, and dynamic tuning trio
Figure 2: Worker AQS perspective, worker lifecycle, and dynamic tuning trio

Invariant: corePoolSize ≤ maximumPoolSize always; violation throws IllegalArgumentException. Therefore:

Scale up: raise max first, then core (raise ceiling before floor).

Scale down: lower core first, then max (lower floor before ceiling).

Encapsulate validation and order in a unified tuning entry point (see template 5.1). Discipline: single step ≤ 25% of current value, observe ≥ 5 minutes — Incident 2's 64→128 jump is the counterexample.

Thread count sizing:

CPU-bound: ≈ cores or cores+1; tuning headroom tiny.

IO-bound: start with N = cores × (1 + wait/compute); measure wait/compute via load test or APM sampling.

Hard ceiling: throughput = min(pool capacity, downstream connection count). If DB pool has 20 connections, 64 threads only yield 20 true concurrent workers; the rest block on connection acquisition. Audit downstream quotas (DB, Redis, third-party) first; thread pool ceiling is the minimum of those.

Queue Sizing and Rejection Strategies: The Buffer Budget

Queue capacity is a buffer budget : it determines how many seconds of burst traffic the system can absorb. Capacity = threads × absorbable seconds × task processing rate. Incident 1's math: 32 threads, 100ms/task, capacity 8000 → absorbs ~25 seconds of delay, but 80k tasks OOM'd. Capacity must satisfy both time budget and memory budget (capacity × per-task memory). Unbounded queue defers both risks to a simultaneous OOM explosion. Production default: ArrayBlockingQueue sized by memory budget ceiling.

Three queue personalities: LinkedBlockingQueue (unbounded default): low-frequency, controllable tasks; requires strict backlog monitoring. SynchronousQueue: zero capacity, direct handoff. Task either taken by idle thread immediately or triggers scale-up/rejection. Suits low-latency, short tasks where rejection is preferred over queueing ( Executors.newCachedThreadPool). ArrayBlockingQueue: bounded, predictable rejection point. Production default.

Selection criterion: "accept as many as possible" → large bounded queue + monitoring; "fail fast when full" → small queue + rejection strategy. Unbounded queue never belongs in production.

Figure 4: Queue sizing, four rejection strategies, and correct submission practices
Figure 4: Queue sizing, four rejection strategies, and correct submission practices

Rejection strategy semantics: AbortPolicy (default): throws RejectedExecutionException; caller must handle — for "message must not be silently lost". CallerRunsPolicy: submitting thread executes the task, creating natural backpressure (submission slows down). Side effect: blocks caller thread; HTTP threads pulled into work slow the whole request chain — avoid in gateways. DiscardPolicy / DiscardOldestPolicy: silent drop — only for logs/metrics; business use = asset loss.

Critical business requires custom handler: persist to DB + rejection counter alert + scheduled replay (template 5.3). Turns rejection from termination into delayed processing.

From execute source: rejection occurs only when core full + queue full + max full. Max and queue capacity are trade-offs: large max + small queue = prefer threads over queueing; small max + large queue = prefer queueing over threads. Rejection ≠ anomaly; it's a normal signal that capacity budget is exhausted — respond by expanding budget or upstream throttling, not by swallowing exceptions.

Upstream defenses (four gates before the pool):

Timeout submission — Future.get with deadline.

Backpressure upfront — semaphore rate limiting before submission.

Pool isolation — core business vs batch processing in separate pools.

Peak shaving upfront — MQ absorbs bursts, pool sees smoothed traffic.

With these, rejection handler triggers rarely; frequent rejection means budget needs increase, not handler change.

Monitoring Metrics and Tuning Loop: Observe to Decide

Dynamic tuning requires visibility. Five mandatory metrics: getActiveCount (active threads); active rate = active/max > 80% → alert (near saturation). getQueue().size() (backlog); > 60% capacity → alert (Incident 1's direct signal). getCompletedTaskCount (cumulative completions); delta gives throughput rate; rate dropping while active count stable → threads stuck in slow tasks. getPoolSize (current thread count); verifies dynamic scaling behavior.

Rejection count (custom handler instrumentation); > 0 → P2 alert. Micrometer 's ExecutorServiceMetrics registers first four in one line; custom platforms use the five APIs. Without these, the pool is a black box — Incident 3's "thought it took effect" is the direct consequence.

Correct tuning loop (five steps):

Observe (five metrics to classify bottleneck type).

Hypothesize (CPU saturated → adding threads useless; high IO wait → adding threads helps; downstream saturated → expand downstream first).

Adjust (via unified entry, max-first/core-first, small steps).

Verify (load test or canary compare throughput and P99).

Persist (if met, new baseline; else rollback to step 1).

Each skipped step maps to an incident: skip hypothesize → Incident 2 (guesswork); skip verify → Incident 3 (no confirmation); skip observe → Incident 1 (no backlog alert). Load test steps (from part 01): define P99 target → find ceiling → start low → ramp stepwise recording inflection → regression verify.

Production Templates: Four Scenarios, Four Code Blocks

5.1 Unified Tuning Entry: Validation + Order + Audit

public class PoolTuner {

public static void apply(
ThreadPoolExecutor pool,
int core, int max) {
// Invariant check: core <= max
if (core < 0 || max < core) {
throw new
IllegalArgumentException(
"bad args: core=" + core
+ " max=" + max);
}
int oldCore = pool.getCorePoolSize();
int oldMax =
pool.getMaximumPoolSize();
if (core > oldCore) {
// Scale up: raise ceiling then floor
pool.setMaximumPoolSize(max);
pool.setCorePoolSize(core);
} else {
// Scale down: lower floor then ceiling
pool.setCorePoolSize(core);
pool.setMaximumPoolSize(max);
}
log.info("tuned: {}/{} -> {}/{}",
oldCore, oldMax, core, max);
}
}

Value: validation at entry, order enforced (scale-up max→core, scale-down core→max), audit log with before/after values. Config center adds effect confirmation: periodic read-back of getCorePoolSize / getMaximumPoolSize vs target; mismatch alerts. "Applied" ≠ "effective"; read-back is the only trustworthy verdict.

5.2 Time-Based Tuning: Night Shrink + Morning Warm-up

// Night shrink, morning warm-up
@Scheduled(cron = "0 0 2 * * ?")
public void nightMode() {
PoolTuner.apply(orderPool, 4, 8);
orderPool.allowCoreThreadTimeOut(true);
}

@Scheduled(cron = "0 30 7 * * ?")
public void dayMode() {
orderPool.allowCoreThreadTimeOut(false);
PoolTuner.apply(orderPool, 16, 32);
// Warm-up: immediately bring core threads up
orderPool.prestartAllCoreThreads();
}

For 10x day/night traffic difference, time-based tuning saves >50% thread resources. Details: night allowCoreThreadTimeOut(true) allows full shrink to zero (idle rebuild cost ~ms, acceptable for insensitive batch jobs); morning prestartAllCoreThreads pre-warms to avoid build-while-queueing; all via PoolTuner entry. Advanced: adaptive — read active rate and queue level, auto small-step scale, but must have ceiling, alerts, audit; fully unsupervised auto-tuning is another incident source.

5.3 Custom Rejection Handler: Persist + Alert + Replay

public class SaveThenRetryPolicy
implements RejectedExecutionHandler {

public void rejectedExecution(
Runnable r,
ThreadPoolExecutor p) {
// 1. Persist: serialize task to DB
long id = taskRepo.save(r);
// 2. Alert: rejection counter
Metrics.counter("pool.reject")
.increment();
// 3. Async replay: scheduled retry
retryScheduler.schedule(
() -> replay(id),
5, TimeUnit.SECONDS);
}
}

Standard for order/payment/notification tasks. Three pillars inseparable:

Persist — store task parameters (not Runnable reference; not serializable, replay state issues).

Alert — rejection count to monitoring, >0 = P2; frequent = budget needs expansion.

Replay — scheduled job re-reads and re-executes, with idempotency and retry cap (prevent infinite loop), mark success.

Comparison: AbortPolicy loses tasks, CallerRuns blocks upstream, custom persist = zero loss — asset-critical businesses have no choice. Remember upstream four gates: rejection handler is insurance, not daily path.

5.4 Metrics Collection: Five Metrics Periodic Export

@Scheduled(fixedRate = 10_000)
public void export() {
gauge("pool.active",
pool.getActiveCount());
gauge("pool.queue",
pool.getQueue().size());
gauge("pool.completed",
pool.getCompletedTaskCount());
gauge("pool.size", pool.getPoolSize());
double ratio = 1.0
* pool.getActiveCount()
/ pool.getMaximumPoolSize();
if (ratio > 0.8) {
alert("pool busy: " + ratio);
}
}

Collection nuances:

Active rate uses double division with 1.0* prefix — two ints divide to 0 or 1, breaking threshold.

10-second interval sufficient (pool state changes at minute granularity); tighter increases storage cost.

Rejection count instrumented in handler (event-driven, no loss), not polled here.

Multi-pool systems use poolName as tag dimension; one alert rule covers all.

In Grafana, these curves turn tuning from "gut feel" to "data-driven": active rate hugging max = scale signal; queue rising while active rate low = threads stuck in slow tasks (check downstream); completed slope dropping = throughput degradation.

Eight-Point Production Review Checklist (One Veto Fails)

Queue bounded? (Unbounded = OOM countdown)

Rejection strategy non-default? (Default Abort at minimum needs catch + alert)

Threads have business names? ( ThreadFactory naming; jstack readable) — highest frequency failure: piles of pool-1-thread-N make troubleshooting guesswork.

Five metrics collected?

Tuning entry converged to PoolTuner? (Business code never touches setters directly)

Thread count matches downstream quotas?

Load tested with real workload? (Wait/compute ratio measured)

Graceful shutdown implemented? ( shutdown + awaitTermination + fallback shutdownNow)

Core Source Code: Four Key Implementations

1. Worker Class Definition — Thread and Lock Fusion

private final class Worker
extends AbstractQueuedSynchronizer
implements Runnable {
final Thread thread;
Runnable firstTask;

Worker(Runnable firstTask) {
setState(-1); // disable interrupt until runWorker
this.firstTask = firstTask;
thread = getThreadFactory()
.newThread(this);
}

public void run() { runWorker(this); }

// state: 0=idle (interruptible) 1=running task
protected boolean isHeldExclusively() {
return getState() != 0;
}
protected boolean tryAcquire(int unused) {
setState(1); // non-reentrant
return true;
}
protected boolean tryRelease(int unused) {
setExclusiveOwnerThread(null);
setState(0);
return true;
}
void lock() { acquire(1); }
void unlock() { release(1); }
}

Worker merges thread and lock. Two details:

Constructor setState(-1) — prevents premature interruption before runWorker starts (-1 makes isHeldExclusively true, interruptIdleWorkers 's tryLock fails). runWorker clears state first, then opens to interrupts. tryAcquire directly setState(1) without CAS — worker lock only contended by its own thread (single-threaded contention), volatile write suffices; legitimate AQS simplification.

Part 04's AQS skeleton runs full cycle here: acquire/release/isHeldExclusively all used.

2. setCorePoolSize Source — Dynamic Tuning Real Semantics

// setCorePoolSize (JDK 17 simplified)
public void setCorePoolSize(
int corePoolSize) {
if (corePoolSize < 0)
throw new IllegalArgumentException();
int delta = corePoolSize
- this.corePoolSize;
this.corePoolSize = corePoolSize;
if (workerCountOf(ctl.get())
> corePoolSize) {
// Shrink: interrupt idle workers to exit naturally
interruptIdleWorkers();
}
else if (delta > 0L) {
// Grow: if queue has backlog, add workers
int k = Math.min(delta,
workQueue.size());
while (k-- > 0
&& addWorker(null, true)) { }
}
}

Source reveals two counter-intuitive behaviors: Grow branch proactively adds workers — if queue has backlog ( workQueue.size() > delta ), directly addWorker(null, true) to create core threads to consume backlog. This is the mechanism guaranteeing "scale-up reduces queue level" (corrects Incident 3's cognition: core increase with backlog triggers active consumption). Shrink only interrupts idle workers — interruptIdleWorkers iterates workers, tries tryLock ; held lock (running task) skipped, waits for natural exit. Thus tuning effect speed depends on queue depth and task duration: scale-up fast (backlog triggers immediate add), scale-down slow (wait for idle + task completion) — basis for "effect confirmation" time budget. 3. getTask Source — Thread Reclamation Decision Core <code>// getTask (JDK 17 simplified) private Runnable getTask() { boolean timedOut = false; for (;;) { int c = ctl.get(); // State check: SHUTDOWN and queue empty if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) { decrementWorkerCount(); return null; // triggers thread exit } int wc = workerCountOf(c); boolean timed = allowCoreThreadTimeOut || wc > corePoolSize; Runnable r = timed ? workQueue.poll(keepAliveTime, NANOSECONDS) : workQueue.take(); // core blocks indefinitely if (r != null) return r; timedOut = true; // poll timeout -> return null -> exit } } }</code> This is the complete secret of "auto-shrink": timed flag binary choice — allowCoreThreadTimeOut enabled or current workers > core → use poll(keepAliveTime) timed wait; else take() indefinite block. poll timeout returns null, worker exits via runWorker , processWorkerExit cleans up — if worker count still ≥ core or pool shutting down, no replacement, thread count naturally drops. allowCoreThreadTimeOut(true) enables "full reclaim" by making first condition always true — all threads timed wait, low-traffic collective timeout exit. Outer for(;;) loop re-reads ctl each iteration; shutdown event and queue drain perceived in same cycle — graceful shutdown response latency = one task cycle. 4. execute Source — Rejection Trigger Point <code>// execute (JDK 17 simplified) public void execute(Runnable command) { int c = ctl.get(); // STEP 1: worker count < core, create thread directly if (workerCountOf(c) < corePoolSize) { if (addWorker(command, true)) return; c = ctl.get(); } // STEP 2: enqueue if (isRunning(c) && workQueue.offer(command)) { int recheck = ctl.get(); // Recheck: pool shut down after enqueue? if (!isRunning(recheck) && remove(command)) reject(command); else if (workerCountOf(recheck) == 0) addWorker(null, false); } // STEP 3: queue full, try expand to max else if (!addWorker(command, false)) // STEP 4: reject reject(command); }</code> Three state rechecks each have purpose: STEP 1 failure re-reads ctl — addWorker may fail due to pool shutdown; new state drives subsequent branches. STEP 2 post-enqueue recheck — handles race where pool shuts down exactly after enqueue: remove + reject returns task to caller (ghost task in queue); if worker count zero, adds a null-task worker to consume enqueued tasks. STEP 3 addWorker(command, false) — non-core worker carries first task directly, explaining why peak new tasks may have lower latency (bypass queue). Reject only triggers when core full + queue full + max full — understanding this combo gives formula basis for capacity planning (max vs queue trade-off). Seven Cost Accounts: Dynamic Tuning ROI Unbounded Queue Account. Incident 1 OOM + 80k lost tasks; fix to ArrayBlockingQueue(2000) + persist rejection = half day. Lesson: "default ≠ safe"; LinkedBlockingQueue default capacity in doc line 3, but no default config monitors backlog. Guesswork Tuning Account. Incident 2 64→128 doubled P99 +30% and wasted 25% CPU. Five-step loop each step ~10 min; skipping any step costs "rollback + postmortem". Formula gives start; load test gives answer. Effect Confirmation Account. Incident 3 "thought effective" cost a week of false observation + postmortem. Read-back + audit < 50 lines; highest ROI in tuning system. "Applied" vs "effective" separated by queue backlog and idle thread exit time. Time-Based Tuning Account. 10x day/night traffic, night shrink cuts resident thread cost >50% (thread ~1MB stack + scheduling overhead). Warm-up ms cost avoids peak backlog; night reclaim minute wait saves resources; both ends pay off. Rejection Strategy Account. Abort easy but loses tasks; CallerRuns zero code but blocks upstream; custom persist 50 lines = zero loss. Asset-critical math: task loss cost vs 50-line maintenance — former always larger. Monitoring Account. Five metrics 30 lines code → "tuning by charts, backlog detected in minutes, effect verifiable". Incident 1 had 40-minute window from backlog to OOM; any queue level alert would have caught it. Black-box operation is the common root of all thread pool incidents. Cognition Account. Worker AQS view runs part 04 skeleton in minimal scene; getTask / setCorePoolSize source turns "dynamic tuning" from doc description into reasonable mechanism. Compound interest in troubleshooting: knowing why shrink slow, grow fast, every alert anomaly explainable. Total investment (bounded queue + custom rejection + five metrics + unified entry) ≤ 2 dev days; prevents three real incidents directly — highest ROI in series. 20 Interview Questions (with Answers) Key Q&A highlights: Q1: setCorePoolSize runtime change immediate? Scale-up immediate if backlog (source adds workers); scale-down gradual (only idle interrupted, busy finish). "Effective" = new tasks new rules, stock digested. Q2: Why Worker extends AQS? Gives each worker a non-reentrant lock: state 0 idle, 1 busy. interruptIdleWorkers uses tryLock to test idle; shutdown only interrupts idle — graceful shutdown built on this lock. Part 04 AQS skeleton minimal application. Q3: setState(-1) in constructor? Prevents premature kill by shutdown interrupt before runWorker . -1 makes isHeldExclusively true, tryLock fails, interrupt blocked. runWorker clears state first, then opens to interrupts. Defensive initialization. Q4: Core vs non-core in getTask ? Core ( workerCount ≤ core ) uses take() indefinite block; non-core uses poll(keepAliveTime) timeout returns null → exit. allowCoreThreadTimeOut(true) forces all to poll branch, pool can shrink to zero. Q5: allowCoreThreadTimeOut principle and cost? Principle: timed flag true, all threads timed wait, low traffic timeout exit → zero threads. Cost: rebuild on traffic return has ms overhead; sudden spike in "no thread + empty queue" moment can only reject or wait — suitable for predictable traffic patterns (time-based), combine with warm-up. Q6: When prestartAllCoreThreads ? Need "immediately fill core": morning peak warm-up (avoid build-while-queueing), pre-load test steady state, post-scale-up immediate backlog consumption. setCorePoolSize grow only adds on new tasks; warm-up is proactive trigger. Q7: Bounded queue capacity sizing? Dual budget: time budget = capacity × task duration / threads (max seconds of processing delay absorbable); memory budget = capacity × task object size (max heap). Take smaller under both constraints, leave monitoring reaction margin (60% level alert). Unbounded queue not no capacity — OOM as ceiling. Q8: SynchronousQueue traits and use cases? Zero capacity direct handoff: offer must have concurrent take to succeed, else immediate fail → new task either taken by idle thread or triggers scale-up/rejection. newCachedThreadPool uses it for "no queue, on-demand threads". Suits low-latency, short tasks, prefer rejection over queueing; long tasks cause thread explosion. Q9: Four rejection strategies selection? AbortPolicy throws exception, caller must sense — messages cannot silently drop; CallerRunsPolicy caller executes, natural backpressure — tolerable slowdown, but blocks HTTP threads, gateways avoid; Discard/DiscardOldest silent drop — only logs/metrics droppable; critical business (order/payment) must custom: persist + counter alert + scheduled replay. Q10: CallerRunsPolicy backpressure mechanism and risk? Backpressure: rejection makes caller execute task, during which it cannot submit new tasks → upstream submission rate naturally pulled down = free rate limiting. Risk: ① slow task occupies caller thread, HTTP thread occupied → whole request chain latency; ② backpressure propagates to gateway → user-facing timeouts. Suits internal chains, not user-facing entry. Q11: Custom RejectedExecutionHandler three must-dos? ① Persist: serialize task params to DB (store params not Runnable ref; replay needs idempotency); ② Alert: rejection counter to monitoring, >0 = P2; ③ Replay: scheduled job re-reads and re-executes, with retry cap and idempotency, mark success. All three inseparable: persist without replay = delayed loss; alert without persist = know lost but can't recover. Q12: execute full flow? ① workerCount < core : addWorker(core) create thread execute; ② Enqueue: offer success then recheck state (pool shut down → remove + reject; worker count 0 → add consumer); ③ Queue full: addWorker(max) create non-core (carries first task); ④ Max full: reject execute handler. Reject only when core full + queue full + max full triple condition. Q13: Why scale-up max then core? Invariant core ≤ max always; violation throws IllegalArgumentException . Scale-up core first exceeding current max → immediate exception; raise max (ceiling) then core (floor) legal. Scale-down reverse. Encapsulate order in unified entry, don't rely on memory. Q14: Dynamic tuning "not effective" common causes? ① Only changed core/max unaware stock behavior unchanged: backlog same, busy threads untouched; ② Listener exception swallowed (config center callback throws no log); ③ Changed pool replica (multi-instance only one updated); ④ Effective but unconfirmed — missing read-back compare. Fix: unified entry + change audit + effect confirmation (read-back params vs target). Q15: Time-based tuning implementation? Scheduled jobs: night shrink + allowCoreThreadTimeOut(true) allow full reclaim; morning restore params + prestartAllCoreThreads warm-up. All via PoolTuner entry (scheduled job is also business caller). Advanced: adaptive — read active rate and queue level auto small-step adjust, but must have ceiling, alerts, audit; fully unsupervised auto-tune = incident source. Q16: Thread count how much? CPU-bound ≈ cores or cores+1, tuning space small; IO-bound N = cores × (1 + wait/compute) start, ratio measured not guessed. Harder constraint: downstream ceiling: pool throughput = min(pool capacity, downstream connections) . DB pool 20 connections → threads >20 just move wait from pool to connection queue. Align thread count with downstream quotas; excess concurrency use semaphore at submission, not let threads block waiting. Q17: Why downstream connections cap thread count? Thread concurrency ultimately limited by contested downstream resources: 20 connections, 21st thread blocks on acquire — doesn't burn CPU but consumes memory, pollutes monitoring (active count falsely high). Correct: align thread count with downstream quotas; excess concurrency intercepted by semaphore at submission. Q18: Five mandatory metrics? getActiveCount (active rate >80% alert), getQueue().size() (backlog >60% capacity alert), getCompletedTaskCount (delta = throughput rate), getPoolSize (current threads, verify dynamic scaling), rejection count (handler instrument, >0 = P2). Active rate calc: multiply 1.0 first to avoid int division truncation. Micrometer one-liner registers first four. Q19: Graceful shutdown how? shutdown() : reject new, interrupt idle, drain queue — gentle; awaitTermination with timeout (e.g., 30s); timeout → shutdownNow() : interrupt all, drain queue return unexecuted list (log or persist). Foundation: Worker AQS lock: interruptIdleWorkers only breaks state=0 idle. Spring ThreadPoolTaskExecutor encapsulates this flow. Q20: Why ThreadFactory naming? Troubleshooting first entry: jstack , logs, monitoring with pool-1-thread-N anonymous threads cannot correlate business — one process dozen pools, locating slow task pure guess. Naming convention: domain-purpose-index (e.g., order-notify-3 ). Lowest cost standard (one ThreadFactory few lines), highest frequency fail in eight-point checklist. One-Page Cheat Sheet Worker view: Thread pool thread = Worker (extends AQS + Runnable); state 0/1 = idle/busy lock; interruptIdleWorkers uses tryLock to test idle; shutdown only stops idle; getTask take/poll binary decides core vs non-core; allowCoreThreadTimeOut enables full pool reclaim. Dynamic tuning: Three setters all runtime callable; effective = new tasks new rules, stock digested; scale-up max then core, scale-down core then max; core ≤ max invariant; unified entry (validation+order+audit) + read-back confirmation + small step (≤1/4) + observe 5 min; warm-up via prestartAllCoreThreads . Queue and rejection: Capacity = min(time budget, memory budget); unbounded = OOM as ceiling; SynchronousQueue zero capacity direct handoff; reject at core full + queue full + max full; CallerRuns natural backpressure but blocks caller; critical business custom handler: persist + counter alert + replay. Observability loop: Five metrics: active rate (>80% alert), queue level (>60% alert), throughput rate, current thread count, rejection count; active rate math multiply 1.0 first; five-step loop: observe → hypothesize → adjust → verify → persist; bottleneck judgment: CPU full add threads useless, IO wait high add threads helps, downstream full expand downstream first. This article upgrades thread pool from "one-time config" to "continuously running system": Worker AQS lock explains shutdown and interrupt mechanism; three setters' source semantics define "effective" boundary; queue and rejection are buffer budget ledger; five metrics and five-step loop turn tuning from mysticism into engineering. Three incidents' shared lesson isn't "parameters set wrong", but "treating a live system as dead config" — bounded, observable, tunable, confirmable, four pieces complete, thread pool enters production door. Next article "Concurrent Container Practice" enters JUC container family: ConcurrentHashMap CAS + synchronized fine-grained locking, CopyOnWriteArrayList copy-on-write and read-scene adaptation, BlockingQueue family selection, and "if container fits don't hand-roll locks" decision checklist.

About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

MonitoringLoad Testingthread poolJava concurrencyDynamic TuningQueue SizingRejection StrategiesWorker AQS

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion