Java Thread Pool ExecutorService: thread execution order

advertisements

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?


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.