bool addWorker()

in activemq-cpp/src/main/decaf/util/concurrent/ThreadPoolExecutor.cpp [1123:1197]


        bool addWorker(Runnable* firstTask, bool core) {
            retry:
            for (;;) {
                int c = ctl.get();
                int rs = this->runStateOf(c);

                // Check if queue empty only if necessary.
                if (rs >= SHUTDOWN && !(rs == SHUTDOWN && firstTask == NULL && !workQueue->isEmpty())) {
                    return false;
                }

                for (;;) {
                    int wc = this->workerCountOf(c);
                    if (wc >= CAPACITY || wc >= (core ? this->corePoolSize : this->maxPoolSize)) {
                        return false;
                    }
                    if (compareAndIncrementWorkerCount(c)) {
                        goto success;
                    }
                    c = ctl.get();  // Re-read ctl
                    if (runStateOf(c) != rs) {
                        goto retry;
                    }
                    // else CAS failed due to workerCount change; retry inner loop
                }
            }

            success:

            Pointer<Worker> w(new Worker(this, firstTask));
            Pointer<Thread> t = w->thread;

            mainLock.lock();
            try {
                // Recheck while holding lock. Back out on ThreadFactory failure or if
                // shut down before lock acquired.
                int c = ctl.get();
                int rs = runStateOf(c);

                if (t == NULL || (rs >= SHUTDOWN && !(rs == SHUTDOWN && firstTask == NULL))) {
                    decrementWorkerCount();
                    tryTerminate();
                    t.reset(NULL);
                    w.reset(NULL);
                    mainLock.unlock();
                    return false;
                }

                workers.add(w.release());

                int s = workers.size();
                if (s > largestPoolSize) {
                    largestPoolSize = s;
                }

            } catch(Exception& ex) {
                mainLock.unlock();
                throw;
            }

            t->start();

            mainLock.unlock();

            // It is possible (but unlikely) for a thread to have been added to
            // workers, but not yet started, during transition to STOP, which
            // could result in a rare missed interrupt, because Thread::interrupt
            // is not guaranteed to have any effect on a non-yet-started Thread
            // (see Thread#interrupt).
            if (runStateOf(ctl.get()) == STOP && !t->isInterrupted()) {
                t->interrupt();
            }

            return true;
        }