WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Core Java · Advanced · question 53 of 100

What is a thread pool in Java? How does it work?

📕 Buy this interview preparation book: 100 Core Java questions & answers — PDF + EPUB for $5

In Java, a thread pool is a group of pre-initialized worker threads that are available to perform a set of tasks. A thread pool is used to reduce the overhead of creating a new thread for each task, which can be expensive in terms of memory and processing power. By using a thread pool, a set of worker threads are already created, and tasks can be submitted to the pool to be executed by the next available thread.

The main components of a thread pool are the worker threads, a task queue, and a thread pool manager. The worker threads are responsible for executing the tasks submitted to the pool, and the task queue is used to hold tasks until a worker thread is available to process them. The thread pool manager is responsible for controlling the behavior of the thread pool, such as the number of worker threads and the size of the task queue.

Here’s an example of how to create a thread pool in Java using the ThreadPoolExecutor class:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadPoolExample {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(5);

        for (int i = 0; i < 10; i++) {
            Runnable worker = new WorkerThread("" + i);
            executor.execute(worker);
        }

        executor.shutdown();
        while (!executor.isTerminated()) {
        }

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

class WorkerThread implements Runnable {
    private String message;

    public WorkerThread(String s) {
        this.message = s;
    }

    public void run() {
        System.out.println(Thread.currentThread().getName() 
            + " (Start) message = " + message);
        processMessage();
        System.out.println(Thread.currentThread().getName() + " (End)");
    }

    private void processMessage() {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

In this example, we create a ThreadPoolExecutor with a fixed pool size of 5 threads using the Executors.newFixedThreadPool() method. We then create 10 worker threads, each with a unique message, and submit them to the executor using the execute() method. The WorkerThread class implements the Runnable interface, and each worker thread sleeps for 2 seconds to simulate work being done.

After submitting all tasks, we call shutdown() on the executor to prevent any new tasks from being submitted, and then wait for all tasks to finish using isTerminated(). Finally, we print a message indicating that all threads have finished processing.

Overall, thread pools are a useful tool for managing the execution of a large number of tasks in a concurrent environment, and can help improve the performance and scalability of Java applications.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Core Java interview — then scores it.
📞 Practice Core Java — free 15 min
📕 Buy this interview preparation book: 100 Core Java questions & answers — PDF + EPUB for $5

All 100 Core Java questions · All topics