@@ -291,11 +291,13 @@ private Worker borrowWorker(WorkerKey key) throws IOException, InterruptedExcept
291
291
while (!idleWorkers .isEmpty ()) {
292
292
// LIFO: It's better to re-use a worker as often as possible and keep it hot, in order to
293
293
// profit from JIT optimizations as much as possible.
294
- worker = idleWorkers .takeLast ();
294
+ // This cannot be null because we already checked that the queue is not empty.
295
+ worker = idleWorkers .peekLast ();
295
296
// We need to validate with the passed in `key` rather than `worker.getWorkerKey()`
296
297
// because the former can contain a different combined files hash if the files changed.
297
298
if (factory .validateWorker (key , worker )) {
298
299
acquired .incrementAndGet ();
300
+ idleWorkers .remove (worker );
299
301
break ;
300
302
}
301
303
invalidateWorker (worker , /* shouldShrinkPool= */ false );
@@ -335,7 +337,14 @@ private synchronized void returnWorker(WorkerKey key, Worker worker) {
335
337
return ;
336
338
}
337
339
338
- activeSet .remove (worker );
340
+ if (activeSet .contains (worker )) {
341
+ activeSet .remove (worker );
342
+ } else {
343
+ throw new IllegalStateException (
344
+ String .format (
345
+ "Worker %s (id %d) is not in the active set" ,
346
+ worker .getWorkerKey ().getMnemonic (), worker .getWorkerId ()));
347
+ }
339
348
340
349
PendingWorkerRequest pendingReq = waitingQueue .poll ();
341
350
if (pendingReq != null ) {
@@ -356,7 +365,14 @@ private synchronized void invalidateWorker(Worker worker, boolean shouldShrinkPo
356
365
}
357
366
358
367
// If it isn't idle, then we're destroying an active worker.
359
- activeSet .remove (worker );
368
+ if (activeSet .contains (worker )) {
369
+ activeSet .remove (worker );
370
+ } else {
371
+ throw new IllegalStateException (
372
+ String .format (
373
+ "Worker %s (id %d) is not in the active set" ,
374
+ worker .getWorkerKey ().getMnemonic (), worker .getWorkerId ()));
375
+ }
360
376
361
377
// We don't want to shrink the pool to 0.
362
378
if (shouldShrinkPool && getEffectiveMax () > 1 ) {
0 commit comments