简体   繁体   中英

Java scheduled threadpool executor internal queue

I want to write a program that runs every 30 minutes. I am using java scheduled threadpool executor to process the tasks that i submit to the executor.

I have been looking at what the official docs say https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ThreadPoolExecutor.html

and i have run into a dilemma.

Lets say i have submitted 5 tasks to the queue and i have defined 10 threads in the thread pool.

  1. Is there a likelyhood that one of the tasks shall be performed twice

  2. Does the threadpool executor make sure that a task is removed when it has been processed by one of the threads or must i remove the task myself once it has been processed.

Having the task removed is desirable since i wouldn't like old tasks to still be in the queue 30 minutes later.

It will be executed only once, the executor will remove it automatically.

This is not explicitly documented, while the doc implys it:

Executes the given task sometime in the future.

Executors.newFixedThreadPool() creates a new ThreadPoolExecutor using a LinkedBlockingQueue .

From Executors.newFixedThreadPool() :

public static ExecutorService newFixedThreadPool(int nThreads) {
    return new ThreadPoolExecutor(nThreads, nThreads,
                                  0L, TimeUnit.MILLISECONDS,
                                  new LinkedBlockingQueue<Runnable>());
}

When tasks are submitted for executions, the ThreadPoolExecutor will add them to this queue. Further, the worker threads will take tasks from this queue and execute them.

From ThreadPoolExecutor.getTask() :

private Runnable getTask() {
  // ...
        try {
            Runnable r = timed ?
                workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
                workQueue.take();
            if (r != null)
                return r;
            timedOut = true;
        } catch (InterruptedException retry) {
            timedOut = false;
        }
    }
}

As per BlockingQueue.take() contract, taking an element from the queue implies removing it as well.

/**
 * Retrieves and removes the head of this queue, waiting if necessary
 * until an element becomes available.
 *
 * @return the head of this queue
 * @throws InterruptedException if interrupted while waiting
 */
E take() throws InterruptedException;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM