Example #1
0
  protected <T> T timedCall(Callable<T> c, long timeout, TimeUnit timeUnit)
      throws InterruptedException, ExecutionException, TimeoutException {

    FutureTask<T> task = new FutureTask<T>(c);
    try {
      THREAD_POOL.execute(task);
      return task.get(timeout, timeUnit);
    } finally {
      task.cancel(true);
    }
  }
Example #2
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());
  }
  public static void main(String[] args) throws Exception {
    int counter = 0;
    while (true) {
      Thread outThread = null;
      Thread errThread = null;
      try {
        // org.pitest.mutationtest.instrument.MutationTestUnit#runTestInSeperateProcessForMutationRange

        // *** start slave

        ServerSocket commSocket = new ServerSocket(0);
        int commPort = commSocket.getLocalPort();
        System.out.println("commPort = " + commPort);

        // org.pitest.mutationtest.execute.MutationTestProcess#start
        //   - org.pitest.util.CommunicationThread#start
        FutureTask<Integer> commFuture = createFuture(commSocket);
        //   - org.pitest.util.WrappingProcess#start
        //       - org.pitest.util.JavaProcess#launch
        Process slaveProcess = startSlaveProcess(commPort);
        outThread = new Thread(new ReadFromInputStream(slaveProcess.getInputStream()), "stdout");
        errThread = new Thread(new ReadFromInputStream(slaveProcess.getErrorStream()), "stderr");
        outThread.start();
        errThread.start();

        // *** wait for slave to die

        // org.pitest.mutationtest.execute.MutationTestProcess#waitToDie
        //    - org.pitest.util.CommunicationThread#waitToFinish
        System.out.println("waitToFinish");
        Integer controlReturned = commFuture.get();
        System.out.println("controlReturned = " + controlReturned);
        // NOTE: the following won't get called if commFuture.get() fails!
        //    - org.pitest.util.JavaProcess#destroy
        outThread.interrupt(); // org.pitest.util.AbstractMonitor#requestStop
        errThread.interrupt(); // org.pitest.util.AbstractMonitor#requestStop
        slaveProcess.destroy();
      } catch (Exception e) {
        e.printStackTrace(System.out);
      }

      // test: the threads should exit eventually
      outThread.join();
      errThread.join();
      counter++;
      System.out.println("try " + counter + ": stdout and stderr threads exited normally");
    }
  }
Example #4
0
  public boolean cancel(boolean mayInterruptIfRunning) {
    if (future == null)
      throw new UnsupportedOperationException(
          "You cannot cancel this task before calling future()");

    return future.cancel(mayInterruptIfRunning);
  }
Example #5
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) {
    }
  }
  public void afterExecute(Runnable r, Throwable t) {
    super.afterExecute(r, t);

    // exceptions wrapped by FutureTask
    if (r instanceof FutureTask) {
      try {
        ((FutureTask) r).get();
      } catch (InterruptedException e) {
        throw new AssertionError(e);
      } catch (ExecutionException e) {
        logger.error("Error in executor futuretask", e);
      }
    }

    // exceptions for non-FutureTask runnables [i.e., added via execute() instead of submit()]
    if (t != null) {
      logger.error("Error in ThreadPoolExecutor", t);
    }
  }