Multithreading - Executors

Concurrency api comes with a new feature called executor that helps in initializing and controlling the execution of threads. Similar to connection pools, there come thread pools.

Executor Framework


At the top of the hierarchy is the Executor interface. It comes with a single execute() method. It provides the functionality such that we can remove manual creation of threads.

execute(Runnable r) - provide a runnable class and it will manage its thread creation & execution

Next is the Executors class. It is a static utility class (similar to Collections) which provides several static factory methods to create various type of Thread Pool implementation in Java.

ExecutorService newCachedThreadPool() - returns a thread pool that creates new threads as needed.

ExecutorService newFixedThreadPool(int num) - returns a thread pool with threads as specified.

ExecutorService newScheduledThreadPool(int num) - returns a thread pool that can schedule                                                                                                    commands to run as per scheduled time.

ExecutorService newSingleThreadExecutor() - returns a thread pool with single thread.


The next class is ExecutorService. It extends the Executor interface and provides with the following methods :

shutdown() - terminates the threads after completion of all pending tasks. will not take new tasks.
shutdownNow() - attempts to terminate immediately

ExecutorService executorService = Executors.newFixedThreadPool(10);
List<MyThreadImplementingRunnableInterface> list = new ArrayList<MyThreadImplementingRunnableInterface>();for(int i=0; i< 100; i++) {
    list.add(new MyThreadImplementingRunnableInterface("Thread " + i));}

for(MyThreadImplementingRunnableInterface myThreadImplementingRunnableInterface : list) {
    executorService.submit(myThreadImplementingRunnableInterface);}

An example for the executorservice and how to create thread pool can be found here

Comments

Popular posts from this blog

Collection Framework - HashSet And LinkedHashSet class

Collection Framework - Cursors in Java

Hashed data structures