Let us consider a scenario where you want to make multiple
service calls and combine the results at the end.
There are multiple ways how this can be achieved, we are
going to see how we can do the same using Future and ExecutorService in java.
Let us first understand how and where Future class has to be
used.
As per Javadoc a Future is “A Future represents
the result of an asynchronous computation. Methods are provided to check if the
computation is complete, to wait for its completion, and to retrieve the result
of the computation. The result can only be retrieved using method get when the
computation has completed, blocking if necessary until it is ready.
Cancellation is performed by the cancel method. Additional methods are provided to determine if
the task completed normally or was cancelled. Once a computation has completed,
the computation cannot be cancelled. If you would like to use a Future for the sake
of cancellability but not provide a usable result, you can declare types of the
form
Future
and return null as a result of the underlying task.”
Example use cases can be when
you have to make a database call which will take more time and a REST web service
call will also has to be called.
You can use Futures to make
asynchronous calls so that both the operations can happen asynchronously.
The result of the async call
can be retrieved by using the get() method.
Please note that the get()
call will be a blocking call and hence has to be used after submitting the
threads to the ExecutorService.
We will also be using
Callable interface which is similar to Runnable interface but can return any
object and also handle Exception.
Let’s see an example with java
multithreading using ExecutorService and Future.
The below ServiceExecutor class implements Callable
interface.
Consider this as a class which is used to make some REST web
service calls and will return the result of the service. We are just returning
the name in this example.
import java.util.concurrent.Callable;
public class ServiceExecutor implements Callable{
private
String name;
public ServiceExecutor(String name){
this.name = name;
}
public String call() throws Exception {
//make service call and return the response
return this.name;
}
}
public class ServiceExecutor implements Callable
public ServiceExecutor(String name){
this.name = name;
}
public String call() throws Exception {
//make service call and return the response
return this.name;
}
}
In the below FutureTask class we are using ExecutorService
from the Executor framework.
We are initializing a pool with 2 threads and submitting it to
the pool.
After submitting both the callable objects to the thread
pool and once the execution completes, we are getting the result back using
get() method and concatenating it using string builder to print it.
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class FutureTask { public static void main(String[] args) { ExecutorService executorService = Executors.newFixedThreadPool(2); //Thread 1 ServiceExecutor executor1 = new ServiceExecutor("thread 1"); FuturefirstResult = executorService.submit(executor1) ; //Thread 2 ServiceExecutor executor2 = new ServiceExecutor("thread 2"); FuturesecondResult = executorService.submit(executor2) ; StringBuilder sb = new StringBuilder(); try { sb.append(firstResult.get()).append(" ") .append(secondResult.get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } System.out.println("Final output: "+sb.toString()); //shut down the executor service executorService.shutdown(); } }
ReplyDeletethe result 2019 of class 8th will be online after 10:00 am on 31st March. View your result just by entering your roll number.