Monday, October 22, 2012

how to return from the method when a timeout has occured

usecase : when we have a method abc() , and caller of this method will wait for 10 min for the resposne from this method, once the time has expired , then caller won't wait for the method response and return from the method.

solution : this can implemented as follows


example :




import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class TimeOutTesting {

public static void main(String[] args){

ExecutorService executor = Executors.newSingleThreadExecutor();
Callable<Object> task = new Callable<Object>() {
  public Object call() {
     return gettheCOntext();
  }
};
Future<Object> future = executor.submit(task);
try {
  Object result = future.get(0, TimeUnit.MILLISECONDS);
 
  System.out.println("hi how are you");
  System.out.println(result.toString());
} catch (TimeoutException ex) {
  System.out.println("time out exception has occured");
}
catch(Exception e)
{System.out.println("Exception has occured");}
finally {
  future.cancel(false); // may or may not desire this
}

}

public static String gettheCOntext()
{
String ramesh="ramesh";
try {
Thread.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ramesh;
}

}



Monday, October 15, 2012