Master java skills

ExecutorService and Future

In Runnable interface, we have run method which doesn’t return any value. Sometimes, we need to return some value. In that situation, there is an interface called Callable which has call method.

Signature of call() method

V call() throws Exception;

Callable interface

package java.util.concurrent;

@FunctionalInterface
public interface Callable<V> {
    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    V call() throws Exception;
}

Executor Service Example

Write a callable task class

package com.sks.executor;

import java.util.concurrent.Callable;

public class CallableTask implements Callable<String> {
    @Override
    public String call() throws Exception {
        Thread.sleep(4000);
        return " this line is executed by : " + Thread.currentThread().getName();
    }
}

Test Class

package com.sks.executor;

import java.util.concurrent.*;

public class CallableTest {

    public static void main(String[] args) {

        Callable task = new CallableTask();

        ExecutorService service = Executors.newFixedThreadPool(10);

        Future<String> value = service.submit(task);

        System.out.println("main proceeded");

        String result = null;
        try {
            result = value.get();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        } finally {
            service.shutdown();
        }

        System.out.println(result);

        System.out.println("main ended gracefully");

    }
}

Output: