user3469157
user3469157

Reputation: 139

Java thread pool size (Executors)

I have an application that has 3 threads which I'm going to switch over to be managed by ScheduledExecutorService. When creating an instance of this you must specific the thread pool size but what is this? Does this mean if I'm planning on running 3 tasks I should create a thread pool size of 3 one for each?

Upvotes: 3

Views: 7215

Answers (1)

Neeraj Jain
Neeraj Jain

Reputation: 7730

Assuming You have created ScheduledExecutorService like this

ScheduledExecutorService executorService = Executors.newFixedThreadPool(10);

executorService.execute(new Runnable() {
    public void run() {
        System.out.println("Asynchronous task");
    }
});

executorService.shutdown();

Now what is happening here :

  • First an ExecutorService is created using the newFixedThreadPool() factory method. This creates a thread pool with 10 threads executing tasks.
  • Second, an anonymous implementation of the Runnable interface is passed to the execute() method. This causes the Runnable to be executed by one of the threads in the ExecutorService.

Thread pools manage a pool of worker threads. The thread pools contains a work queue which holds tasks waiting to get executed.

Now Coming to :

Does this mean if I'm planning on running 3 tasks I should create a thread pool size of 3 one for each?

Yes so that all 3 task can be executed parallely .

Now here is a nice article about How big should our thread pool be?

Upvotes: 2

Related Questions