Callable Interface in java

The Callable is an interface which is available in java.util.concurrent package. It is similar to Runnable Interface but there is some difference.

  • Runnable interface has the run() method and its return type is void
  • Callable interface has the call() method and its return type is Future
  • Callable interface can’t be executed using thread class similarly runnable, Through Thread ExecutorService only we can run it.

Sample Code

In below example I try to run the callable object using thread but getting the compile time exception.

package com.samplecoder.threading;

import java.util.concurrent.Callable;

public class ThreadWithCallable {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		Thread t1 = new Thread(new Callable<String>() {

			@Override
			public String call() throws Exception {
				// TODO Auto-generated method stub
				return null;
			}
		})
		
	}

}

Exception

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
	The constructor Thread(new Callable<String>(){}) is undefined
	Syntax error, insert ";" to complete BlockStatements

	at com.samplecoder.threading.ThreadWithCallable.main(ThreadWithCallable.java:10)

Callable with ExecutorService

package com.samplecoder.threading;

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;

public class ThreadWithCallable {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		Callable<String> c1 = new Callable<String>() {

			@Override
			public String call() throws Exception {
				// TODO Auto-generated method stub
				System.out.println("Callable started");
				for(int i=1; i<=10; i++) {
					System.out.println(i);
					Thread.sleep(100);
				}
				return "Completed";
			}
		};
		
		
		ExecutorService executorService = Executors.newFixedThreadPool(3);
		Future<String> result = executorService.submit(c1);
		try {
			System.out.println(result.get());
		} catch (InterruptedException | ExecutionException e) {
			e.printStackTrace();
		}
	}

}

Result

Callable started
1
2
3
4
5
6
7
8
9
10
Completed

Conclusion

Now, you should know what is callable interface and you should able to write some basic java code using the callable interface.