Showing posts with label Callable. Show all posts
Showing posts with label Callable. Show all posts

Thursday, 4 September 2014

Executor and ExecutorService in Java

Executor Framework (java.util.concurrent.Executors) included in jdk1.5. Before explaining what, why and how? I will explain little background about Thread. As you know Thread in java is used for parallel execution in new VM stack and it created by two ways Thread class and Runnable interface. To know more about thread click here
When you use Executor Framework then no need to create Thread explicitly. And multiple thread can execute  tasks concurrently. These multiple Thread maintained inside pool called Thread pool. Once Thread will be allocated to process one task it can't allocated to process other task until Thread is free. Whenever any Thread finish it execution it notify to executor framework to take up another task. Hence we can say that Executor Framework implicitly maintain the Thread allocation for the task.
We can have n number of Treads in the Thread pool. Thread can be reused by multiple time. So, Executor is very useful from performance point of view. because it will save the time to create the Thread again and again, as you know creating Thread inside is very heavy process.
An Executor is normally used instead of explicitly creating threads. For example, rather than invoking new Thread(new(RunnableTask())).start() for each of a set of tasks, you might use:
 Executor executor = anExecutor;
 executor.execute(new RunnableTask1());
 executor.execute(new RunnableTask2());
 
So, java.util.concurrent.ExecutorService provide us the way to execute the task by Thread which present in the pool. And Executors factory class provide the factory method to create the Thread pool.
e.g-

ExecutorService executorService = Executors.newFixedThreadPool(10);

executorService.execute(new Runnable() {
    public void run() {
        System.out.println("Runnable task");
    }
});

executorService.shutdown();
 
ExecutorService is created here using the newFixedThreadPool() factory method. This creates a thread pool with 10 threads executing tasks.
Later on, 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.
And last line we are shutting the executorService.When you are done using the ExecutorService you should shut it down, so the threads do not keep running.

Apart from newFixedThreadPool() factory method some other method are also present in Executors factory class to create the ExecutorService e.g.-
newFixedThreadPool(),
newScheduledThreadPool().
As you have seen in above example that Runnable task is executed by execute() method of executorService. But apart from this we have some other ways to submit/execute the task, which is listed below-
execute(Runnable)- Only Runnable task can be execute by this and it doesn't return any value. as you have seen in above example.

submit(Runnable/Callable)- Runnable and Callable task both can be execute by submit method. and it always return Future.e.g.-
 
Future future = executorService.submit(new Runnable() {
    public void run() {
        System.out.println("Runnable task");
    }
});

future.get(); 

or

Future future = executorService.submit(new Callable(){
    public Object call() throws Exception {
        System.out.println("Callable task");
        return "Callable Result";
    }
});

System.out.println("future.get() = " + future.get());



invokeAny(collection)-
The invokeAny() method takes a collection of Callable objects, or subinterfaces of Callable. Invoking this method does not return a Future, but returns the result of one of the Callable objects. You have no guarantee about which of the Callable's results you get. Just one of the ones that finish.
If one of the tasks complete (or throws an exception), the rest of the Callable's are cancelled.

ExecutorService executorService = Executors.newSingleThreadExecutor();

Set<Callable<String>> callables = new HashSet<Callable<String>>();
 
callables.add(new Callable<String>() {
    public String call() throws Exception {
        return "First task ";
    }
});  
...................
......................
String result = executorService.invokeAny(callables);

System.out.println("result = " + result);

executorService.shutdown(); 
 
invokeAll(collection)-
The 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.
Keep in mind that a task might finish due to an exception, so it may not have "succeeded". There is no way on a Future to tell the difference.

ExecutorService executorService = Executors.newSingleThreadExecutor();

Set<Callable<String>> callables = new HashSet<Callable<String>>();

callables.add(new Callable<String>() {
    public String call() throws Exception {
        return "First task ";
    }
}); 
 
..................................
.................................
 
List<Future<String>> futures = executorService.invokeAll(callables);

for(Future<String> future : futures){
    System.out.println("future.get = " + future.get());
}

executorService.shutdown();

 

Tuesday, 26 August 2014

Difference between Callable and Runnable in java

The first thing both Callable and Runnable are interface. Runnable might be heard a lot because it is used to create Thread. But Callable is added on java5 where as Runnable is present from jdk1.0.

Let's try to understand both -
Runnable- It is a interface and present from jdk1.0.It has run() method where we can execute task. method signature is given below-

public void run()
{
//task
}
here method return type is void
 
When we execute sometask in different thread then we can use Runnable interface but the thread can not return any result in this case because the return type is void.  And this execute by Thread. e.g.

class MyRunnable implements Runnable{
 public void run(){
  System.out.print("runabletask")
 }
 
public static void main (String args[]){

  Thread t= new Thread(new MyRunnable());
  t.start();
 
  //or start runnable by executor
  //ExecutorService executor =  Executors.newFixedThreadPool(2);
  //executor.execute(new MyRunnable());
 }
} 

Callable - It is also a interface which is present from jdk5.0.It has call() method. It is used for parallel execution hence it is part of concurrent api, present in java.util.concurrent package.
Method signature is given below

public V call()throws Exception
{
//task
}
 
here method return type is Generic type V That means, can be passed from parameter of class  This return called future object of java.util.concurrent.Future package. As run method doesn't return any result so, in jdk5.0 introduced Callable.In some situation when we want return some result after thread execution finish then we can use Callable interface.This also execute by Thread. e.g.

class MyCallable implements Callable<String>{ 
 
 public String call()throws Exception{
  System.out.print("callable task")
 }

public static void main(String...args){ 
 ExecutorService executor =  Executors.newFixedThreadPool(2);
 
 List<Future<String>> list = new ArrayList<Future<String>>();
 
 MyCallable  callable = new MyCallable();
 for(int i=0; i< 100; i++){
  Future <String>future = executor.submit(callable);
  list.add(future);
 }
 for(Future <String>future:list){
  try {
    System.out.println(future.get());
  } catch (Exception e) {
    e.printStackTrace();
  }
 }
  executer.shutdown(); 
 } 

To create Thread pool in java Executer class used and These Thread pool will 
hold Thread to execute Callable or Runnable in a thread pool.Since callable or Runnable tasks run in parallel, we have to wait for the returned 
Object in case of Callable. Callable tasks return java.util.concurrent.Future object. 
Using Future we can find out the status of the Callable task and get the 
returned Object. It provides get() method that can wait for the Callable to 
finish and then return the result.

Future also provides cancel() method to cancel the Callable task. There is an overloaded version of get() method
 where we can specify the time to wait for the result, it’s useful to 
avoid current thread getting blocked for longer time. There are isDone() and isCancelled() methods to find out the current status of associated Callable task.