Anupam Banerji
Anupam Banerji

Reputation: 21

Does a Java 8 fixed thread pool always create a fixed number threads?

I'm looking at code for the Java 8 fixed thread pool. Here's a small sample:

    ExecutorService service = Executors.newFixedThreadPool(100);

    try {

        for (int i = 0; i < 10; ++i) {
            service.submit(() -> "In another thread!");
        }

    } catch (Exception e) {
        // Do nothing
    } finally {
        service.shutdown();
    }

The question I have is (in two parts):

a. How many threads will the fixed thread pool object above create? 100? Or just 10?

b. How can I check how many threads have been created?

Upvotes: 2

Views: 1895

Answers (3)

Chris Mowforth
Chris Mowforth

Reputation: 6723

Please don't make assumptions about how an executor will spin up underlying threads in your application code. Just to satisfy your curiosity:

How many threads will the fixed thread pool object above create? 100? Or just 10?

Completely depends on the ThreadFactory used- by default, a fixed thread pool spawns threads lazily. Of course this may change in any subsequent JDK unless otherwise documented. As @EJP said, the only invariant you can rely on is there will be no more than 100 of them.

How can I check how many threads have been created?

There's no way of getting threads dedicated to a particular executor, but from inside the JVM you can use Thread#getAllStackTraces to get a map of call stacks for all live threads. Alternatively use some tool like VisualVM.

Upvotes: 1

corneria
corneria

Reputation: 618

The following are two simple classes that I used as idioms to when learning the ExecutorService, Callable, and Future classes.

You can see that I use a thread pool of size 2, and have 10 items that I need to process. Basically, you create a thread pool, pass in classes that implement Callable, and use the resulting Future as proof of processing. Only two items can be processed at a time, given the thread pool of size 2. You can change the values if you'd like to see the results.

Main.java:

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class Main {

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(2);

        List<Future<String>> lst = new ArrayList<Future<String>>();

        for (int i = 0; i < 10; ++i) {
            Callable<String> callable = new Calling();
            Future<String> future = executorService.submit(callable);
            lst.add(future);
        }

        int futureCount = 0;
        for (Future<String> fut : lst) {
            try {
                futureCount++;
                System.out.println("Processed call() in thread " + fut.get() + ", future number: " + futureCount);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        executorService.shutdown();
        while (!executorService.isTerminated()) {
            // wait, basically
        }

        System.out.println("Finished all threads!");

    }
}

Calling.java

import java.util.concurrent.Callable;

public class Calling implements Callable<String> {

    public Calling() {
    }

    public String call() throws InterruptedException {
        System.out.println("Sleeping thread: " + Thread.currentThread().getName());
        Thread.sleep(2000);
        return Thread.currentThread().getName();
    }

}

Upvotes: 0

user207421
user207421

Reputation: 310913

How many threads will the fixed thread pool object above create? 100? Or just 10?

It isn't specified. All that is specified is that there will never be more than 100.

How can I check how many threads have been created?

There is no API for that. You could get the total thread count before and after, but that could be fuzzy as Java has other reasons for creating threads.

Upvotes: 3

Related Questions