views:

76

answers:

1

The SimpleThreadPool class shipped along with Quartz Scheduler does not have a FIFO behavior. I want to make sure if I keep adding jobs to the scheduler, they are addressed in a First - in - First - out basis. Is there any ThreadPool available for this ? Or is there any other way to achieve this?

+4  A: 

You could achieve this by delegating to a ThreadPoolExecutor with a FIFO queue, as follows :

public class DelegatingThreadPool implements ThreadPool {

private int size = 5; //Fix this up if you like
private final ThreadPoolExecutor executor = new ThreadPoolExecutor(size, size,
                                  0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());

public boolean runInThread(Runnable runnable) {
    synchronized (executor) {
        if (executor.getActiveCount() == size) {
            return false;
        }
        executor.submit(runnable);
        return true;
    }
}

public int blockForAvailableThreads() {
    synchronized (executor) {
        return executor.getActiveCount();
    }
}

public void initialize() throws SchedulerConfigException {
    //noop
}

public void shutdown(boolean waitForJobsToComplete) {
    //No impl provided for wait, write one if you like
    executor.shutdownNow();
}

public int getPoolSize() {
    return size;
}

public void setInstanceId(String schedInstId) {
    //Do what you like here
}

public void setInstanceName(String schedName) {
    //Do what you like here
}

It is possible that the active count of executables will not exactly match the exact number of tasks that are executing. You'd need to add a latch and use the beforeExecute to ensure that the task has started running if this is necessary.

This is a great example, I will try this.
Shamik