java function retry wrapper

import java.util.concurrent.Callable;

/**
 * Created by huahui.yang on 1/29/16.
 */
public class RetryWrapper<A> {
  public A retry(Callable<A> callable) throws Exception {
    A result = null;
    for (int i = 0; i < 3; i++) {
      System.out.println("retry time remain:" + (3 - i));
      try {
        result = callable.call();
        break;
      } catch (Exception e) {
      }
    }
    return result;
  }
}
/**
 * Created by huahui.yang on 1/29/16.
 */
public class JOB {
  public int add(int i, int j) throws Exception {
    throw new Exception("error");
//    return i+j;
  }
}
import java.util.concurrent.Callable;

/**
 * Created by huahui.yang on 1/29/16.
 */
public class JOBExample {
  public static void main(String[] args) throws Exception{
    int i = new RetryWrapper<Integer>().retry(new Callable<Integer>() {
      @Override
      public Integer call() throws Exception {
        return new JOB().add(1,2);
      }
    });
    System.out.print(i);
  }
}

 

posted @ 2016-01-29 12:47  yanghuahui  阅读(630)  评论(0编辑  收藏  举报