sclass ThreadPool { int max = numberOfCores(); new SelfNotifyingSet used; new SelfNotifyingSet free; synchronized int total() { ret l(used)+l(free); } synchronized bool nonFree() { ret empty(free) && max < total(); } event customerMustWaitAlert; void fireCustomerMustWaitAlert { vmBus_send customerMustWaitAlert(this, currentThread()); customerMustWaitAlert(); } synchronized WithAutoCloseable acquireThread() { if (nonFree()) fireCustomerMustWaitAlert(); if (total() < max) used.add(newThread()); sleepWhileEmpty(free); Thread t = assertNotNull(popFirst(free)); used.add(t); ret withAutoCloseable(-> giveThreadBack(t), t); } synchronized void giveThreadBack(Thread t) { used.remove(t); free.add(t); } static Thread newThread() { ret new Thread("Thread Pool Inhabitant " + n2(total()+1)) { }; } }