orbatschow
orbatschow

Reputation: 1537

Java job execution multithreaded with executorservice?

How to i implement such a function ?

I have a dynamic queue which gets filled at unknown times with runnables, which have to be executed. The ExecutorService should only start a limited amount of threads, when the maximum thread size is reached, it should stop executing more threads, until one thread finishes, then the next task should be executed.

So far i came across this:

ExecutorService executor = new ThreadPoolExecutor(20, Integer.MAX_VALUE,
                60L, TimeUnit.SECONDS,
                databaseConnectionQueue);

The ExecutorService is created before the queue is filled, and should stay alive until the queue is deleted, not when its empty, because this can happen. Can anybody help me ?

Upvotes: 0

Views: 153

Answers (2)

Rahul Winner
Rahul Winner

Reputation: 430

I believe you should use FixedThreadPool (Executors.newFixedThreadPool)

As per javadoc [Executors.newFixedThreadPool]

Creates a thread pool that reuses a fixed number of threads operating off a shared unbounded queue. At any point, at most nThreads threads will be active processing tasks. If additional tasks are submitted when all threads are active, they will wait in the queue until a thread is available. If any thread terminates due to a failure during execution prior to shutdown, a new one will take its place if needed to execute subsequent tasks. The threads in the pool will exist until it is explicitly shutdown.

Hope it helps. Thanks.

Upvotes: 0

m0skit0
m0skit0

Reputation: 25873

ThreadPoolExecutor will will not shutdown when it is empty. From the JavaDoc:

A pool that is no longer referenced in a program AND has no remaining threads will be shutdown automatically.

Upvotes: 1

Related Questions