views:

273

answers:

3

I'm working with a java.util.concurrent.ThreadPoolExecutor to process a number of items in parallel. Although the threading itself works fine, at times we've run into other resource constraints due to actions happening in the threads, which made us want to dial down the number of Threads in the pool. I'd like to know if there's a way to dial down the number of the threads while the threads are actually working. I know that you can call setMaximumPoolSize() and/or setCorePoolSize(), but these only resize the pool once threads become idle, but they don't become idle until there are no tasks waiting in the queue.

A: 

I read the documentation of setMaximumPoolSize() and setCorePoolSize(), and it seems like they can produce the behavior you need.

-- EDIT --

My conclusion was wrong: please see the discussion below for details...

Eyal Schneider
The workers will NOT exit immediately. "If the new value is smaller than the current value, excess existing threads will be terminated when they next become idle." As long as there are tasks in the executor, or entering the executor in a timely manner, the workers will not terminate.
Tim Bender
@Tim - yes, that is what Eyal is saying. Does the OP want his existing threads to be terminated without regard? That would not be something that an executor could do even if it wanted. The OP could set a boolean on certain tasks to tell them to end early, and it would probably be a good idea to send an interrupt when that boolean is set. But this is app level logic - not something an executor could do out of hand.
Kevin Day
One other random idea would be if the Executor could throttle a certain number of threads by reducing their priority. That might give the same overall effect. This is just a random idea - it might have huge flaws that I'm not thinking about.
Kevin Day
@Kevin Day, actually @Eyal said they will terminate when they finish their job, this is NOT TRUE. They will grab another task from the queue and begin executing it immediately. If no task is available, they will block waiting for a task for the specified keepAliveTime before finally terminating. The OP wants to shut them down as soon as they are done with the current task. Also, an Executor's job is to execute tasks. Managing Threads is the job of a ThreadPool. The ThreadPool implementation could have been such that each worker thread had to check for permission to stay alive. But it does NOT.
Tim Bender
Tim Bender is summarizing my understanding (based on actual testing) well. -OP
Edward Shtern
You are right guys. just tested it, and saw the same behavior. The documentation of setMaximumPoolSize and setCorePoolSize is a little misleading in my opinion. Specifically the term "idle" is confusing, since a thread that finishes its current task, and blocks waiting for new tasks apparently is not considered idle yet...
Eyal Schneider
argh - bitten by the documentation - sorry about that. I bow to Tim's experience on this one. Your distinction between responsibilities of the TP and the Executor is spot on - thanks.
Kevin Day
@Kevin, "if the Executor could throttle a certain number of threads by reducing their priority" - that is not guaranteed to have any effect (it is platform dependent), and may well have unexpected consequences, so it is not recommended.
Péter Török
+3  A: 

As far as I can tell, this is not possible in a nice clean way.

You can implement the beforeExecute method to check some boolean value and force threads to halt temporarily. Keep in mind, they will contain a task which will not be executed until they are re-enabled.

Alternatively, you can implement afterExecute to throw a RuntimeException when you are saturated. This will effectively cause the Thread to die and since the Executor will be above the max, no new one would be created.

I don't recommend you do either. Instead, try to find some other way of controlling concurrent execution of the tasks which are causing youa problem. Possibly by executing them in a separate thread pool with a more limited number of workers.

Tim Bender
A: 

You absolutely can. Calling setCorePoolSize(int) will change the core size of the pool. Calls to this method are thread-safe and override settings provided to the constructor of ThreadPoolExecutor. If you are trimming the pool size, the remaining threads will shut-down once their current job queue is completed (if they are idle, they will shut-down immediately). If you are increasing the pool size, new threads will be allocated as soon as possible. The timeframe for the allocation of new threads is undocumented — but in the implementation, allocation of new threads is performed upon each call to the execute method.

To pair this with a runtime-tunable job-farm, you can expose this property (either by wrapper or using a dynamic MBean exporter) as a read-write JMX attribute to create a rather nice, on-the-fly tunable batch processor.

To reduce the pool size forcibly in runtime (which is your request), you must subclass the ThreadPoolExecutor and add a disruption to the beforeExecute(Thread,Runnable) method. Interrupting the thread is not a sufficient disruption, since that only interacts with wait-states and during processing the ThreadPoolExecutor task threads do not go into an interruptable state.

I recently had the same problem trying to get a thread pool to forcibly terminate before all submitted tasks are executed. To make this happen, I interrupted the thread by throwing a runtime exception only after replacing the UncaughtExceptionHandler of the thread with one that expects my specific exception and discards it.

/**
 * A runtime exception used to prematurely terminate threads in this pool.
 */
static class ShutdownException
extends RuntimeException {
    ShutdownException (String message) {
        super(message);
    }
}

/**
 * This uncaught exception handler is used only as threads are entered into
 * their shutdown state.
 */
static class ShutdownHandler 
implements UncaughtExceptionHandler {
    private UncaughtExceptionHandler handler;

    /**
     * Create a new shutdown handler.
     *
     * @param handler The original handler to deligate non-shutdown
     * exceptions to.
     */
    ShutdownHandler (UncaughtExceptionHandler handler) {
        this.handler = handler;
    }
    /**
     * Quietly ignore {@link ShutdownException}.
     * <p>
     * Do nothing if this is a ShutdownException, this is just to prevent
     * logging an uncaught exception which is expected.  Otherwise forward
     * it to the thread group handler (which may hand it off to the default
     * uncaught exception handler).
     * </p>
     */
    public void uncaughtException (Thread thread, Throwable throwable) {
        if (!(throwable instanceof ShutdownException)) {
            /* Use the original exception handler if one is available,
             * otherwise use the group exception handler.
             */
            if (handler != null) {
                handler.uncaughtException(thread, throwable);
            }
        }
    }
}
/**
 * Configure the given job as a spring bean.
 *
 * <p>Given a runnable task, configure it as a prototype spring bean,
 * injecting any necessary dependencices.</p>
 *
 * @param thread The thread the task will be executed in.
 * @param job The job to configure.
 *
 * @throws IllegalStateException if any error occurs.
 */
protected void beforeExecute (final Thread thread, final Runnable job) {
    /* If we're in shutdown, it's because spring is in singleton shutdown
     * mode.  This means we must not attempt to configure the bean, but
     * rather we must exit immediately (prematurely, even).
     */
    if (!this.isShutdown()) {
        if (factory == null) {
            throw new IllegalStateException(
                "This class must be instantiated by spring"
                );
        }

        factory.configureBean(job, job.getClass().getName());
    }
    else {
        /* If we are in shutdown mode, replace the job on the queue so the
         * next process will see it and it won't get dropped.  Further,
         * interrupt this thread so it will no longer process jobs.  This
         * deviates from the existing behavior of shutdown().
         */
        workQueue.add(job);

        thread.setUncaughtExceptionHandler(
            new ShutdownHandler(thread.getUncaughtExceptionHandler())
            );

        /* Throwing a runtime exception is the only way to prematurely
         * cause a worker thread from the TheadPoolExecutor to exit.
         */
        throw new ShutdownException("Terminating thread");
    }
}

In your case, you may want to create a semaphore (just for use as a threadsafe counter) which has no permits, and when shutting down threads release to it a number of permits that corresponds to the delta of the previous core pool size and the new pool size (requiring you override the setCorePoolSize(int) method). This will allow you to terminate your threads after their current task completes.

private Semaphore terminations = new Semaphore(0);

protected void beforeExecute (final Thread thread, final Runnable job) {
    if (terminations.tryAcquire()) {
        /* Replace this item in the queue so it may be executed by another
         * thread
         */
        queue.add(job);

        thread.setUncaughtExceptionHandler(
            new ShutdownHandler(thread.getUncaughtExceptionHandler())
            );

        /* Throwing a runtime exception is the only way to prematurely
         * cause a worker thread from the TheadPoolExecutor to exit.
         */
        throw new ShutdownException("Terminating thread");
    }
}

public void setCorePoolSize (final int size) {
    int delta = getActiveCount() - size;

    super.setCorePoolSize(size);

    if (delta > 0) {
        terminations.release(delta);
    }
}

This should interrupt n threads for f(n) = active - requested. If there is any problem, the ThreadPoolExecutors allocation strategy is fairly durable. It book-keeps on premature termination using a finally block which guarantees execution. For this reason, even if you terminate too many threads, they will repopulate.

Scott S. McCoy
Yep, I know that you can make the change and have it take effect once the threads are idle. However what I found was that being "idle" doesn't occur when a thread completes its task, unless there are no other tasks waiting. I was asking if there was any way to have the change take effect immediately, so that even if there are waiting tasks, they will be handled by the new desired number of threads (as in my example, where we wanted to immediately dial down the amount of concurrent resources being used).
Edward Shtern
I have updated my post to describe a solution derived from a problem I recently had which was similar in nature. Please have a look at it.
Scott S. McCoy
I don't get it, why do I get zero karma for this answer? :-(
Scott S. McCoy