Searching...
Friday, 21 March 2014

Java Callable and Future Simple Example

13:27

The Callable interface is similar to java.lang.Runnable, in that both are designed for classes whose instances are potentially executed by another thread. Runable cannot return a result and cannot throw a checked exception. But Callable can return values and throw exceptions. Here is one simple example to use Callable and Future interfaces.

1. CallableExample.java

package 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;
/**
 * 
 * <b>This class helps to understand the feature of Executer service ,Callable
 * and Future interface</>
 * <ul>
 * <li>Below Thread1 class implements Callable interface and override call
 * method to creates thread (Same concept of Runnable interface)</li>
 * <li>The overridden call method returns the current thread name</li>
 * <li>Used ExecutorService and Executors implementation class to create new
 * fixed thread pool</li>
 * <li>Used Executer service instance to submit the Callables and Future used to
 * store the return type</li>
 * 
 * <li></li>
 * 
 * </ul>
 * 
 * @author vinod
 * 
 */
public class CallableExample {
	public static void main(String args[]) throws InterruptedException,
			ExecutionException {
		ExecutorService ex = Executors.newFixedThreadPool(10);
		Thread1 t1 = new Thread1();
		// 10 threads executing the task
		for (int i = 0; i <= 10; i++) {
			Future<String> future = ex.submit(t1);
			System.out.println(future.get());
		}
	}
}
/**
 * Creating threads using link{Callable}
 * @author vinod
 *
 */
class Thread1 implements Callable<String> {
	public String call() throws Exception {
		return Thread.currentThread().getName();
	}
}

2. Output



pool-1-thread-1
pool-1-thread-2
pool-1-thread-3
pool-1-thread-4
pool-1-thread-5
pool-1-thread-6
pool-1-thread-7
pool-1-thread-8
pool-1-thread-9
pool-1-thread-10
pool-1-thread-1


0 comments: