Java Callable Example
June 07, 2022
On this page we will learn using Java Callable
in our application.
1. The
Callable
is a task that returns a result and may throw an exception.
2. The
Callable
is a functional interface whose functional method is call()
. Find the method declaration.
V call() throws Exception
It throws
Exception
if unable to compute a result.
3. The
Callable
is similar to Runnable
. But Runnable
does not return a result and cannot throw a checked exception.
4. The
Callable
can be instantiated with lambda expression, method reference, Executors.callable
and class.
Create Callable
TheCallable
has functional interface call()
that returns value and does not accept argument. We can create Callable
instance in following ways.
1. Using Lambda Expression
Callable<String> task = () -> { System.out.println("Executing Task-1"); return "Success"; };
Suppose we have a class.
class Task { public static int count() { int i = 1; for(; i < 5; i++) { System.out.println(i); } return i; } }
count()
is matching to functional method call()
of Callable
.
We can instantiate
Callable
using method reference as following.
Callable<Integer> myTask = Task::count;
Callable
Interface
Create a class implementing
Callable
interface.
class Task implements Callable<Integer> { @Override public Integer call() throws Exception { int i = 1; for(; i < 5; i++) { System.out.println(i); } return i; } }
Task
class.
Callable<Integer> myTask = new Task();
We can create
Callable
instance using Executors.callable
method that has following declarations.
a.
static Callable<Object> callable(Runnable task)
Callable
that returns null.
b.
static <T> Callable<T> callable(Runnable task, T result)
Callable
that returns specified result.
c.
static Callable<Object> callable(PrivilegedAction<?> action)
Callable
that returns the result of given privileged action.
d.
static Callable<Object> callable(PrivilegedExceptionAction<?> action)
Callable
that returns the result of given privileged exception action.
Example
Runnable runnable = () -> { for(int i = 1 ; i < 5; i++) { System.out.println(i); } }; Callable<String> myTask = Executors.callable(runnable, "Done");
Run Callable
1. The instance ofCallable
can be executed using Java concurrent Future
.
2. The
Future
represents the result of an asynchronous computation. It provides methods to check if the computation is complete, to wait for its completion, and to retrieve the result of the computation.
3. Thread pool is created using
Executors
method such as newCachedThreadPool
, newFixedThreadPool
, newScheduledThreadPool
etc.
Example-1
CallableDemo1.java
package com.concretepage; 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; import java.util.concurrent.TimeUnit; public class CallableDemo1 { public static void main(final String... args) throws InterruptedException, ExecutionException { Callable<String> task1 = () -> { System.out.println("Executing Task-1"); return "Task-1 Finish."; }; Callable<String> task2 = () -> { System.out.println("Executing Task-2"); return "Task-2 Finish."; }; ExecutorService executorService = Executors.newFixedThreadPool(1); Future<String> future1 = executorService.submit(task1); Future<String> future2 = executorService.submit(task2); String output1 = future1.get(); System.out.println(output1); String output2 = future2.get(); System.out.println(output2); executorService.awaitTermination(3, TimeUnit.SECONDS); executorService.shutdownNow(); } }
Executing Task-1 Executing Task-2 Task-1 Finish. Task-2 Finish.
CallableDemo2.java
package com.concretepage; 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; import java.util.concurrent.TimeUnit; public class CallableDemo2 { public static void main(final String... args) throws InterruptedException, ExecutionException { Runnable runnable = () -> { for(int i = 1 ; i < 5; i++) { System.out.println(i); } }; Callable<String> myTask = Executors.callable(runnable, "Done"); ExecutorService executorService = Executors.newCachedThreadPool(); Future<String> future = executorService.submit(myTask); String output = future.get(); System.out.println(output); executorService.awaitTermination(2, TimeUnit.SECONDS); executorService.shutdownNow(); } }
1 2 3 4 Done
CallableDemo3.java
package com.concretepage; 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; import java.util.concurrent.TimeUnit; public class CallableDemo3 { public static void main(final String... args) throws InterruptedException, ExecutionException { Callable<String> myTask = new Task(); ExecutorService executorService = Executors.newSingleThreadExecutor(); Future<String> future = executorService.submit(myTask); String output = future.get(); System.out.println(output); executorService.awaitTermination(3, TimeUnit.SECONDS); executorService.shutdownNow(); } } class Task implements Callable<String> { @Override public String call() throws Exception { System.out.println("Fetching data ..."); return "success"; } }
Fetching data ... success