1.

What Is Threadpool In Java?

Answer»

In a large scale application if each task uses its own thread then allocating and deallocating many thread objects creates a significant memory management OVERHEAD.

Thread pool as the name SUGGESTS provides a set of threads, any task which has to be executed get a thread from this pool.

// creating executor with pool of 2 threads
ExecutorService ex = Executors.newFixedThreadPool(2);
// RUNNING 6 TASKS
ex.execute(new Task());
ex.execute(new Task());
ex.execute(new Task());
ex.execute(new Task());
ex.execute(new Task());
ex.execute(new Task());
//shutting down the executor service
ex.shutdown();

Even if we are running 6 tasks here, all these tasks would be run using the 2 threads from the pool.

In a large scale application if each task uses its own thread then allocating and deallocating many thread objects creates a significant memory management overhead.

Thread pool as the name suggests provides a set of threads, any task which has to be executed get a thread from this pool.

// creating executor with pool of 2 threads
ExecutorService ex = Executors.newFixedThreadPool(2);
// running 6 tasks
ex.execute(new Task());
ex.execute(new Task());
ex.execute(new Task());
ex.execute(new Task());
ex.execute(new Task());
ex.execute(new Task());
//shutting down the executor service
ex.shutdown();

Even if we are running 6 tasks here, all these tasks would be run using the 2 threads from the pool.



Discussion

No Comment Found