Пример #1
0
  /**
   * 异步调用 ,需要返回值,即使步调用Future.get方法,也会处理调用超时问题.
   *
   * @param callable
   * @return 通过future.get()获取返回结果.
   */
  @SuppressWarnings("unchecked")
  public <T> Future<T> asyncCall(Callable<T> callable) {
    try {
      try {
        setAttachment(Constants.ASYNC_KEY, Boolean.TRUE.toString());
        final T o = callable.call();
        // local调用会直接返回结果.
        if (o != null) {
          FutureTask<T> f =
              new FutureTask<T>(
                  new Callable<T>() {
                    public T call() throws Exception {
                      return o;
                    }
                  });
          f.run();
          return f;
        } else {

        }
      } catch (Exception e) {
        throw new RpcException(e);
      } finally {
        removeAttachment(Constants.ASYNC_KEY);
      }
    } catch (final RpcException e) {
      return new Future<T>() {
        public boolean cancel(boolean mayInterruptIfRunning) {
          return false;
        }

        public boolean isCancelled() {
          return false;
        }

        public boolean isDone() {
          return true;
        }

        public T get() throws InterruptedException, ExecutionException {
          throw new ExecutionException(e.getCause());
        }

        public T get(long timeout, TimeUnit unit)
            throws InterruptedException, ExecutionException, TimeoutException {
          return get();
        }
      };
    }
    return ((Future<T>) getContext().getFuture());
  }
Пример #2
0
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    System.out.print("Enter base directory (e.g. /usr/local/jdk5.0/src): ");
    String directory = in.nextLine();
    System.out.print("Enter keyword (e.g. volatile): ");
    String keyword = in.nextLine();

    MatchCounter counter = new MatchCounter(new File(directory), keyword);
    FutureTask<Integer> task = new FutureTask<Integer>(counter);
    Thread t = new Thread(task);
    t.start();
    try {
      System.out.println(task.get() + " matching files.");
    } catch (ExecutionException e) {
      e.printStackTrace();
    } catch (InterruptedException e) {
    }
  }