ScheduledExecutorService pick() { ScheduledExecutorService[] a = executors; if (a == null) { start(); a = executors; if (a == null) { thrownewIllegalStateException("executors uninitialized after implicit start()"); } } if (a != SHUTDOWN) { // ignoring the race condition here, its already random who gets which executor intidx= roundRobin; if (idx == n) { idx = 0; roundRobin = 1; } else { roundRobin = idx + 1; } return a[idx]; } return TERMINATED; }
BoundedState pick() { for (;;) { inta= get(); if (a == DISPOSED) { return CREATING; //synonym for shutdown, since the underlying executor is shut down }
if (!idleQueue.isEmpty()) { //try to find an idle resource BoundedStatebs= idleQueue.pollLast(); if (bs != null && bs.markPicked()) { busyQueue.add(bs); return bs; } //else optimistically retry (implicit continue here) } elseif (a < parent.maxThreads) { //try to build a new resource if (compareAndSet(a, a + 1)) { ScheduledExecutorServices= Schedulers.decorateExecutorService(parent, parent.createBoundedExecutorService()); BoundedStatenewState=newBoundedState(this, s); if (newState.markPicked()) { busyQueue.add(newState); return newState; } } //else optimistically retry (implicit continue here) } else { //pick the least busy one BoundedStates= busyQueue.poll(); if (s != null && s.markPicked()) { busyQueue.add(s); //put it back in the queue with updated priority return s; } //else optimistically retry (implicit continue here) } } }