Tuesday, May 2, 2023

Understanding Completable Futures in JAVA?

Runnable

Runnable interface was introduced in JDK 1.0 to execute a block of code in a separate thread to achieve multi threading in java. It is present inside java.lang package. It is a functional interface and has a single method run() which returns void that means nothing.

Callable 

Callable interface was introduced in JDK 5 to return a response back form an executing thread. It is present inside java.util.concurrent package.  It is also a functional interface and has a single method call() which returns an object returned by the method.

  • Example to get Future object using callable interface via FutureTask
 
public class TestCallable {
    public static void main(String[] args) throws Exception {
MyCallable myCallable = new MyCallable();
FutureTask<Integer> futureTask = new FutureTask(myCallable);
Thread thread = new Thread(futureTask);
thread.start();
int i = futureTask.get();
System.out.println(i);
}
}

class MyCallable implements Callable{
@Override
public Integer call() throws Exception {
return 105;
}
}
  • Example to get Future object using callable interface via Executors framework
public class TestCallable {
public static void main(String[] args) throws ExecutionException, InterruptedException {
Callable<String> callable = () -> {return "Return some result";};
ExecutorService executorService = Executors.newSingleThreadExecutor();
Future<String> future = executorService.submit(callable);
String s = future.get();
System.out.println(s);
executorService.shutdown();
}
}


No comments:

Post a Comment

SpringBoot Application Event Listeners

When a spring boot application starts few events occurs in below order ApplicationStartingEvent ApplicationEnvironmentPreparedEvent Applicat...