Vijay Kansal
Vijay Kansal

Reputation: 839

Java Thread Pool ExecutorService: Threads execution order

As we create a Thread pool using Java's Executor service and submit threads to this thread pool, what is the order in which those threads get executed?

I want to ensure that threads submitted first, execute first. For example, in the code below, I want first 5 threads to get executed first, followed by the next 5 threads and so on...

// Create a thread pool of 5 threads.
ScheduledExecutorService exService = Executors.newScheduledThreadPool(5, new ModifiedThreadFactory("ReadThreadPool"));

// Create 100 threads.
MyThread[] threads = createMyThreads(100);

// Submit these 100 threads to thread pool for execution.
for(MyThread thread : threads) {
    exService.submit(thread);
}

Does Java's Thread Pool provide any API for this purpose, or do we need to implement a FIFO queue at our end to achieve this. If Java's thread pool does not provide any such functionality, I am really interested to understand the reason behind the non-existence of this functionality as it appears like a very common use-case to me. Is it technically not possible (which I think is quite unlikely), or is it just a miss?

Upvotes: 1

Views: 4605

Answers (2)

omu_negru
omu_negru

Reputation: 4770

Threads do not get executed. Threads are the entities running taska like Runnable and Callable . Submiting such a task to a executor service will put it in it's inner BlockingQueue until it gets picked up by a thread from it's thread pool. This will still tell you nothing about the order of execution as different classes can do different things while implementing Runnable

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 692121

That's the default behavior. ScheduledThreadExecutor (that you're using although you're not scheduling anything) extends from ThreadPoolExecutor. Tasks submitted to a ThreadPoolExecutor are stored in a BlockingQueue until one thread is available to take them and execute them. And queues are FIFO.

This is decscribed in details in the javadoc.

Upvotes: 5

Related Questions