Tuesday 23 May 2017

Executor Service in Java

Hello Guys!!! Hope You all are doing well. Today I am going to discuss ExecutorService in java Thread.

The java.util.concurrent.ExecutorService interface represents an asynchronous execution mechanism which is capable of executing tasks in the background. An ExecutorService is very similar to a thread pool.

A simple Java ExectorService example

ExecutorService executorService = Executors.newFixedThreadPool(10);
executorService.execute(new Runnable() {
public void run() {
System.out.println("Asynchronous task");
}
});
executorService.shutdown();
  • 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.
A thread delegating a task to an ExecutorService for asynchronous execution.

Once the thread has delegated the task to the ExecutorService, the thread continues its own execution independent of the execution of that task.
ExecutorService Implementations
ExecutorService is an interface, we need to its implementations in order to make any use of it. The ExecutorService has the following implementation in the java.util.concurrent package:

  • ThreadPoolExecutor
  • ScheduledThreadPoolExecutor
Creating an ExecutorService
We can use the Executors factory class to create ExecutorService instances . Below are a few examples:

  • ExecutorService executorSerAvice1 = Executors.newSingleThreadExecutor();
  • ExecutorService executorService2 = Executors.newFixedThreadPool(10);
  • ExecutorService executorService3 = Executors.newScheduledThreadPool(10);
ExecutorService Usage
There are a few different ways to delegate tasks for execution to an ExecutorService:

  • execute(Runnable)
  • submit(Runnable)
  • submit(Callable)
  • invokeAny(...)
  • invokeAll(...)
execute(Runnable) method takes:- a java.lang.Runnable object, and executes it asynchronously. There is no way of obtaining the result of the executed Runnable, if necessary.
submit(Runnable) method:- also takes a Runnable implementation, but returns a Future object. This Future object can be used to check if the Runnable as finished executing.
submit(Callable) method:- similar to the submit(Runnable) method except that its call() method can return a result. The Runnable.run() method cannot return a result.
The Callable's result can be obtained via the Future object returned by the submit(Callable) method.
invokeAny():- method takes a collection of Callable objects, or subinterfaces of Callable. This method does not return a Future, but returns the result of one of the Callable objects. We have no guarantee about which of the Callable's results we get. Just one of the ones that finish.
invokeAll():- method invokes all of the Callable objects you pass to it in the collection passed as parameter. The invokeAll() returns a list of Future objects via which you can obtain the results of the executions of each Callable.
Dowload Example code 
package com.sks.softsolution.example4;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ExecutorServiceExample {

    public static void main(String[] args) {

        //example 1
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        // here we are using execute(runnable) method 
        executorService.execute(new RunnableThread("execute: "));

        //Example 2
        Future future = null;
        try {
            Thread.sleep(1000);
            System.out.println(".............................................");
            //ExecutorService submit() example, returns a Future object
            future = executorService.submit(new RunnableThread("submit: "));
            try {
                //returns current status of work.
                System.out.println("future.IsDone "+future.isDone());
                //returns null if the task has finished correctly.
                System.out.println("future.get() "+future.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(".............................................");

        //Example 3 
        //ExecutorService Callable example
        future = executorService.submit(new CallableThread());
        try {
            System.out.println("Callable: future.get() = " + future.get());
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        System.out.println(".............................................");

        //Example 4
        //ExecutorService invokeAny() method example
        Set<Callable<String>> callables = new HashSet<Callable<String>>();
        callables.add(new Callable<String>() {
            public String call() throws Exception {
                return "Task 1";
            }
        });
        callables.add(new Callable<String>() {
            public String call() throws Exception {
                return "Task 2";
            }
        });
        callables.add(new Callable<String>() {
            public String call() throws Exception {
                return "Task 3";
            }
        });

        String result = null;
        try {
            result = executorService.invokeAny(callables);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        System.out.println("invokeAny: result = " + result);
        System.out.println(".............................................");

        // Example 5
        // ExecutorService invokeAll() method example
        List<Future<String>> futures;
        try {
            futures = executorService.invokeAll(callables);
            for (Future<String> future1 : futures) {
                System.out.println("invokeAll: future.get = " + future1.get());
            }
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }

        //Shutdown executor to avoid memory leak
        executorService.shutdown();

    }

    // Runnable thread
    static class RunnableThread implements Runnable {
        String name = "Runnable:";

        RunnableThread(String methodName){
            name = methodName;
        }

        @Override
        public void run() {
            for (int cnt = 0; cnt < 5; cnt++) {
                System.out.println(name + cnt);
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }
    }


 // Callable thread
    static class CallableThread implements Callable<Integer> {
        @Override
        public Integer call() {
            int cnt = 0;
            for (; cnt < 5; cnt++) {
                System.out.println("call:" + cnt);
            }
            return cnt;
        }
    }
}
Please read inline comment for proper understanding of above code.
executorService.shutdown() 
When you are done using the ExecutorService you should shut it down, so the threads do not keep running.
As for example, if your application is started via a main() method and your main thread exits your application, the application will keep running if you have an active ExexutorService in your application. The active threads inside this ExecutorService prevents the JVM from shutting down.
To terminate the threads inside the ExecutorService you call its shutdown() method. The ExecutorService will not shut down immediately, but it will no longer accept new tasks, and once all threads have finished current tasks, the ExecutorService shuts down. All tasks submitted to the ExecutorService before shutdown() is called, are executed.
If you want to shut down the ExecutorService immediately, you can call the shutdownNow() method. This will attempt to stop all executing tasks right away, and skips all submitted but non-processed tasks. There are no guarantees given about the executing tasks. Perhaps they stop, perhaps the execute until the end. It is a best effort attempt.

Thanks
Saurabh
Happy Coding!!!
Give your comment.

1 comment:

  1. hello,
    i just want to say that you have clearly mention the process very clearly and i also found it is very much easy to understand. keep sharing.

    android app development company in chennai

    ReplyDelete

Build a Custom Kernel Module for Android

Hi Guys!!!Hope you are doing well !!!. Today I will describe how you can write a custom kernel module(Hello world) for Android and load it a...