| Refresh | Home EGTry.com

use FutureTask to run a task in a new thread, and return results and capture exception


/*
 * Copyright@ 2011 www.egtry.com
 */

package egtry.thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;


//execute a task
//1. if it finishes successfully, get the return value
//2. if if fails and throws exception, get the error message
//3. if it does not finish before a certain period, then timeout
public class FutureTask1Test {

  public static void main(String[] args) {
	  ExecutorService service=Executors.newFixedThreadPool(10);
	  
	  FutureTask<Integer> task1=new FutureTask<Integer>(new EasyJob());
	  service.submit(task1);
	  
	  FutureTask<Integer> toolongTask=new FutureTask<Integer>(new TooLongJob());
	  service.submit(toolongTask);
	  try {
		  Integer rc=task1.get();
		  System.out.println("EasyJob return value: "+rc);
		  
		  Integer rc2=toolongTask.get(1, TimeUnit.SECONDS);
		  System.out.println("TooLongJob return value: "+rc2);
	  } catch (ExecutionException e1) {
		  System.out.println("failed in execution: "+e1.getMessage());
	  } catch (InterruptedException e2) {
		  System.out.println("InterruptedException");
	  } catch (TimeoutException e3) {
		  System.out.println("TimeoutException: "+e3.getMessage());
	  }
	  System.out.println("Done");

  }
  
  public static class EasyJob implements Callable {
	@Override
	public Integer call() throws Exception {
		return 10;
	}
  }
  
  public static class TooLongJob implements Callable {
	@Override
	public Integer call() throws Exception {
		try {
			Thread.sleep(10*1000);
		} catch (InterruptedException e) {
			
		}
		return 11;
	}
  }
  
}



Output

EasyJob return value: 10
TimeoutException: null
Done