@Test
  public void testLeaseCancel() throws Exception {
    final LocalConnFactory connFactory = Mockito.mock(LocalConnFactory.class);

    final HttpConnection conn1 = Mockito.mock(HttpConnection.class);
    Mockito.when(conn1.isOpen()).thenReturn(true);
    Mockito.when(connFactory.create(Mockito.eq("somehost"))).thenReturn(conn1);

    final LocalConnPool pool = new LocalConnPool(connFactory, 1, 1);

    final Future<LocalPoolEntry> future1 = pool.lease("somehost", null);
    final GetPoolEntryThread t1 = new GetPoolEntryThread(future1);
    t1.start();

    t1.join(GRACE_PERIOD);
    Assert.assertTrue(future1.isDone());
    final LocalPoolEntry entry1 = t1.getEntry();
    Assert.assertNotNull(entry1);

    final Future<LocalPoolEntry> future2 = pool.lease("somehost", null);
    final GetPoolEntryThread t2 = new GetPoolEntryThread(future2);
    t2.start();

    Thread.sleep(5);

    Assert.assertFalse(future2.isDone());
    Assert.assertFalse(future2.isCancelled());

    future2.cancel(true);
    t2.join(GRACE_PERIOD);
    Assert.assertTrue(future2.isDone());
    Assert.assertTrue(future2.isCancelled());
    future2.cancel(true);
    future2.cancel(true);
  }
 // TODO: should this actually throw only ExecutionException?
 public <T> T callWithTimeout(
     Callable<T> callable, long timeoutDuration, TimeUnit timeoutUnit, boolean amInterruptible)
     throws Exception {
   checkNotNull(callable);
   checkNotNull(timeoutUnit);
   checkArgument(timeoutDuration > 0, "bad timeout: " + timeoutDuration);
   Future<T> future = executor.submit(callable);
   try {
     if (amInterruptible) {
       try {
         return future.get(timeoutDuration, timeoutUnit);
       } catch (InterruptedException e) {
         future.cancel(true);
         throw e;
       }
     } else {
       Future<T> uninterruptible = Futures.makeUninterruptible(future);
       return uninterruptible.get(timeoutDuration, timeoutUnit);
     }
   } catch (ExecutionException e) {
     throw Throwables.throwCause(e, true);
   } catch (TimeoutException e) {
     future.cancel(true);
     throw new UncheckedTimeoutException(e);
   }
 }
  /** {@inheritDoc} */
  public void destroy() {
    started.set(false);
    destroyed.set(true);
    releaseExternalResources();
    if (notifierFuture != null) {
      notifierFuture.cancel(true);
    }

    if (asyncWriteFuture != null) {
      asyncWriteFuture.cancel(true);
    }

    if (bc != null) {
      bc.destroy();
    }

    if (broadcasterCache != null) {
      broadcasterCache.stop();
    }
    resources.clear();
    broadcastOnResume.clear();
    messages.clear();
    asyncWriteQueue.clear();
    delayedBroadcast.clear();
    broadcasterCache = null;

    if (BroadcasterFactory.getDefault() != null) {
      BroadcasterFactory.getDefault().remove(this, name);
    }

    if (currentLifecycleTask != null) {
      currentLifecycleTask.cancel(true);
    }
  }
  // This method generally should only be called by HubProvideFactory.removeHubRequestMonitor()
  public void destroy() {
    if (systemData != null) systemData.system.destroy();

    synchronized (this) {
      if (createSystemFuture != null) createSystemFuture.cancel(true);
      if (queryOperation != null) queryOperation.cancel();
      queryOperation = null;

      if (gracePeriodFuture != null) gracePeriodFuture.cancel(true);
      gracePeriodFuture = null;

      if (gracePeriodExpiredFuture != null) gracePeriodExpiredFuture.cancel(true);
      gracePeriodExpiredFuture = null;

      if (activateInterestOperation != null) activateInterestOperation.cancel();
      activateInterestOperation = null;
      if (provider != null) provider.destroy();
      provider = null;
      if (hubConfig != null) hubProvideFactory.removeHubConfig(hubConfig);
      hubConfig = null;

      if (hubRequestRequestor != null) hubRequestRequestor.destroy();
      hubRequestRequestor = null;
    }
  }
  @Override
  public V compute(final A arg) throws InterruptedException {
    // TODO Auto-generated method stub
    Future<V> f = cache.get(arg);
    if (f == null) {
      Callable<V> eval =
          new Callable<V>() {
            public V call() throws InterruptedException {
              return c.compute(arg);
            }
          };

      FutureTask<V> ft = new FutureTask<V>(eval);
      f = ft;
      cache.putIfAbsent(arg, ft);
      ft.run();
    }
    try {
      return f.get(5000, TimeUnit.MILLISECONDS);
    } catch (CancellationException e) {
      f.cancel(true);
      cache.remove(arg, f); // 当被取消时,把原来的值移除,以免造成污染
    } catch (ExecutionException e) {
      e.printStackTrace();
    } catch (TimeoutException e) {
      System.out.println("执行超时");
      f.cancel(true);
      cache.remove(arg, f);
    }
    return null;
  }
  public void checkAndResumePsicquicTasks() {
    List<Future> currentRunningTasks = new ArrayList<Future>(runningTasks);

    for (Future<PsicquicCountResults> f : currentRunningTasks) {
      try {
        PsicquicCountResults results = f.get(threadTimeOut, TimeUnit.SECONDS);

        if (results.isImex()) {
          if (results.isImexResponding() && results.getImexCount() > 0) {
            countInOtherImexDatabases += results.getImexCount();
            otherImexDatabasesWithResults++;
          } else if (!results.isImexResponding()) {
            nonRespondingImexDatabases++;
          }
        }

        if (results.isServiceResponding() && results.getPsicquicCount() > 0) {
          countInOtherDatabases += results.getPsicquicCount();
          otherDatabasesWithResults++;
        } else if (!results.isServiceResponding()) {
          nonRespondingDatabases++;
        }

        runningTasks.remove(f);
      } catch (InterruptedException e) {
        log.error("The psicquic task was interrupted, we cancel the task.", e);
        this.nonRespondingDatabases++;
        this.nonRespondingImexDatabases++;
        if (!f.isCancelled()) {
          f.cancel(false);
        }
        runningTasks.remove(f);
      } catch (ExecutionException e) {
        log.error("The psicquic task could not be executed, we cancel the task.", e);
        if (!f.isCancelled()) {
          f.cancel(false);
        }
        runningTasks.remove(f);
      } catch (TimeoutException e) {
        log.error("Service task stopped because of time out " + threadTimeOut + "seconds.");
        this.nonRespondingDatabases++;
        this.nonRespondingImexDatabases++;

        if (!f.isCancelled()) {
          f.cancel(false);
        }
        runningTasks.remove(f);
      } catch (Throwable e) {
        log.error("The psicquic task could not be executed, we cancel the task.", e);
        if (!f.isCancelled()) {
          f.cancel(false);
        }
        runningTasks.remove(f);
      }
    }
  }
    @Override
    public void run() {
      while (MemcachedConnector.this.isStarted()) {
        ReconnectRequest request = null;
        try {
          request = MemcachedConnector.this.waitingQueue.take();

          InetSocketAddress address = request.getInetSocketAddressWrapper().getInetSocketAddress();

          if (!MemcachedConnector.this.removedAddrSet.contains(address)) {
            boolean connected = false;
            Future<Boolean> future =
                MemcachedConnector.this.connect(request.getInetSocketAddressWrapper());
            request.setTries(request.getTries() + 1);
            try {
              log.warn(
                  "Trying to connect to "
                      + address.getAddress().getHostAddress()
                      + ":"
                      + address.getPort()
                      + " for "
                      + request.getTries()
                      + " times");
              if (!future.get(MemcachedClient.DEFAULT_CONNECT_TIMEOUT, TimeUnit.MILLISECONDS)) {
                connected = false;
              } else {
                connected = true;
                break;
              }
            } catch (TimeoutException e) {
              future.cancel(true);
            } catch (ExecutionException e) {
              future.cancel(true);
            } finally {
              if (!connected) {
                rescheduleConnectRequest(request);
              } else {
                continue;
              }
            }
          } else {
            log.warn("Remove invalid reconnect task for " + address);
            // remove reconnect task
          }
        } catch (InterruptedException e) {
          // ignore,check status
        } catch (Exception e) {
          log.error("SessionMonitor connect error", e);
          rescheduleConnectRequest(request);
        }
      }
    }
Exemple #8
0
  public void cancelOutstandingRequests() {
    synchronized (outstandingDownloads) {
      for (Future<Drawable> downloadFuture : outstandingDownloads.values()) {
        downloadFuture.cancel(true);
      }
      outstandingDownloads.clear();

      for (Future<?> drawFuture : outstandingDraws.values()) {
        drawFuture.cancel(true);
      }
      outstandingDraws.clear();
    }
  }
  /** Method onDelete. */
  @Override
  protected void onDelete() {
    if (_victimSpawnKeyBoxTask != null) {
      _victimSpawnKeyBoxTask.cancel(false);
      _victimSpawnKeyBoxTask = null;
    }

    if (_onDeadEventTask != null) {
      _onDeadEventTask.cancel(false);
      _onDeadEventTask = null;
    }

    super.onDelete();
  }
  /**
   * Starts a process from its builder. <span>The default redirects of STDOUT and STDERR are
   * started</span>
   *
   * <p>It is possible to wait for the process to get to a warmed-up state via {@linkplain
   * Predicate} condition on the STDOUT
   *
   * @param name The process name
   * @param processBuilder The process builder
   * @param linePredicate The {@linkplain Predicate} to use on the STDOUT Used to determine the
   *     moment the target app is properly warmed-up. It can be null - in that case the warmup is
   *     skipped.
   * @param timeout The timeout for the warmup waiting
   * @param unit The timeout {@linkplain TimeUnit}
   * @return Returns the initialized {@linkplain Process}
   * @throws IOException
   * @throws InterruptedException
   * @throws TimeoutException
   */
  public static Process startProcess(
      String name,
      ProcessBuilder processBuilder,
      final Predicate<String> linePredicate,
      long timeout,
      TimeUnit unit)
      throws IOException, InterruptedException, TimeoutException {
    Process p = processBuilder.start();
    StreamPumper stdout = new StreamPumper(p.getInputStream());
    StreamPumper stderr = new StreamPumper(p.getErrorStream());

    stdout.addPump(new LineForwarder(name, System.out));
    stderr.addPump(new LineForwarder(name, System.err));
    CountDownLatch latch = new CountDownLatch(1);
    if (linePredicate != null) {
      StreamPumper.LinePump pump =
          new StreamPumper.LinePump() {
            @Override
            protected void processLine(String line) {
              if (latch.getCount() > 0 && linePredicate.test(line)) {
                latch.countDown();
              }
            }
          };
      stdout.addPump(pump);
      stderr.addPump(pump);
    }
    Future<Void> stdoutTask = stdout.process();
    Future<Void> stderrTask = stderr.process();

    try {
      if (timeout > -1) {
        long realTimeout = Math.round(timeout * Utils.TIMEOUT_FACTOR);
        if (!latch.await(realTimeout, unit)) {
          throw new TimeoutException();
        }
      }
    } catch (TimeoutException | InterruptedException e) {
      System.err.println("Failed to start a process (thread dump follows)");
      for (Map.Entry<Thread, StackTraceElement[]> s : Thread.getAllStackTraces().entrySet()) {
        printStack(s.getKey(), s.getValue());
      }
      stdoutTask.cancel(true);
      stderrTask.cancel(true);
      throw e;
    }

    return p;
  }
  /** 存入一个对象 */
  private boolean _set(String key, Object value) {
    // mc1.delete(key);
    // mc2.delete(key);
    boolean ret = false;
    Future<Boolean> f = mc1.set(key, expHour * 60 * 60, value);
    Future<Boolean> f2 = mc2.set(key, expHour * 60 * 60, value);
    try {
      boolean fs1 = f.get(opTimeout, TimeUnit.SECONDS);
      boolean fs2 = f2.get(opTimeout, TimeUnit.SECONDS);
      ret = fs1 || fs2;

      if (!fs1) {
        log.info(
            "[FAIL]CACHE SET FAIL:server1 set failed: "
                + "Key="
                + key
                + "\tValue="
                + value.toString());
      } else if (!fs2) {
        log.info(
            "[FAIL]CACHE SET FAIL:server2 set failed: "
                + "Key="
                + key
                + "\tValue="
                + value.toString());
      }
    } catch (TimeoutException e) {
      // Since we don't need this, go ahead and cancel the
      // operation. This
      // is not strictly necessary, but it'll save some work on
      // the server.
      log.info("[FAIL]time out when getting objects from cache server2...");
      f.cancel(false);
      f2.cancel(false);
      // Do other timeout related stuff
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      log.error("[ERROR]exception when setting fengchao cache - thread been interrupted...", e);
      f.cancel(false);
      f2.cancel(false);
    } catch (ExecutionException e) {
      // TODO Auto-generated catch block
      log.error(
          "[ERROR]exception when setting fengchao cache - exception when getting status...", e);
      f.cancel(false);
      f2.cancel(false);
    } catch (Exception e) {
      log.error("[ERROR]exception when setting fengchao cache - other exceptions...", e);
      f.cancel(false);
      f2.cancel(false);
    }

    if (value != null) {
      log.info("MemCacheServiceImpl.set,key=" + key + ",value=" + value.getClass());
    } else {
      log.info("MemCacheServiceImpl.set,key=" + key + ",value=null");
    }
    return ret;
  }
  /** {@inheritDoc} */
  @Override
  public void setBroadcasterLifeCyclePolicy(final BroadcasterLifeCyclePolicy lifeCyclePolicy) {
    this.lifeCyclePolicy = lifeCyclePolicy;
    if (currentLifecycleTask != null) {
      currentLifecycleTask.cancel(false);
    }

    if (lifeCyclePolicy.getLifeCyclePolicy()
            == BroadcasterLifeCyclePolicy.ATMOSPHERE_RESOURCE_POLICY.IDLE
        || lifeCyclePolicy.getLifeCyclePolicy()
            == BroadcasterLifeCyclePolicy.ATMOSPHERE_RESOURCE_POLICY.IDLE_DESTROY) {

      int time = lifeCyclePolicy.getTimeout();
      if (time == -1) {
        throw new IllegalStateException("BroadcasterLifeCyclePolicy time is not set");
      }

      final AtomicReference<Future<?>> ref = new AtomicReference<Future<?>>();
      currentLifecycleTask =
          bc.getScheduledExecutorService()
              .scheduleAtFixedRate(
                  new Runnable() {

                    @Override
                    public void run() {
                      try {
                        if (resources.isEmpty()) {
                          notifyEmptyListener();
                          notifyIdleListener();

                          if (lifeCyclePolicy.getLifeCyclePolicy()
                              == BroadcasterLifeCyclePolicy.ATMOSPHERE_RESOURCE_POLICY.IDLE) {
                            releaseExternalResources();
                            logger.debug("Applying BroadcasterLifeCyclePolicy IDLE policy");
                          } else {
                            notifyDestroyListener();

                            destroy();
                            /**
                             * The value may be null if the timeout is too low. Hopefully next
                             * execution will cancel the task properly.
                             */
                            if (ref.get() != null) {
                              currentLifecycleTask.cancel(true);
                            }

                            logger.debug("Applying BroadcasterLifeCyclePolicy IDLE_DESTROY policy");
                          }
                        }
                      } catch (Throwable t) {
                        logger.warn("Scheduled BroadcasterLifeCyclePolicy exception", t);
                      }
                    }
                  },
                  time,
                  time,
                  lifeCyclePolicy.getTimeUnit());
      ref.set(currentLifecycleTask);
    }
  }
Exemple #13
0
 /** Releases the references held by this DGCAckHandler. */
 synchronized void release() {
   if (task != null) {
     task.cancel(false);
     task = null;
   }
   objList = null;
 }
  @Override
  public void process(
      final HasCancellation cancellation, OrcsSession session, TransactionData txData) {
    try {
      final Set<Long> datas = new LinkedHashSet<Long>();
      txData
          .getChangeSet()
          .accept(
              new OrcsVisitorAdapter() {
                @Override
                public void visit(AttributeData data) {
                  IAttributeType type = types.getByUuid(data.getTypeUuid());
                  if (types.isTaggable(type)) {
                    datas.add(data.getVersion().getGammaId());
                  }
                }
              });

      List<Future<?>> futures = indexer.indexResources(session, types, datas).call();
      for (Future<?> future : futures) {
        if (cancellation != null && cancellation.isCancelled()) {
          future.cancel(true);
        } else {
          // Wait for execution to complete
          future.get();
        }
      }
    } catch (Exception ex) {
      logger.error(ex, "Error indexing transaction [%s]", txData);
    }
  }
 public void done(Callable callable) {
   isDone.set(true);
   if (reaperFuture != null) {
     reaperFuture.cancel(true);
   }
   super.done();
 }
  private void closeImmediately0() {
    // We need to close the channel immediately to remove it from the
    // server session's channel table and *not* send a packet to the
    // client.  A notification was already sent by our caller, or will
    // be sent after we return.
    //
    super.close(true);

    // We also need to close the socket.
    Socket.close(handle);

    try {
      if ((forwarder != null) && (!forwarder.isDone())) {
        forwarder.cancel(true);
      }
    } finally {
      forwarder = null;
    }

    try {
      if ((forwardService != null) && shutdownForwarder) {
        Collection<?> runners = forwardService.shutdownNow();
        if (log.isDebugEnabled()) {
          log.debug("Shut down runners count=" + GenericUtils.size(runners));
        }
      }
    } finally {
      forwardService = null;
      shutdownForwarder = false;
    }
  }
  @Override
  public void close() {
    boolean shouldSendDelete;
    Future<?> future;
    synchronized (this) {
      shouldSendDelete = !closed;

      closed = true;

      future = this.future;

      this.future = null;

      lastUpdate = DateTime.now();
    }

    if (future != null && !future.isDone()) {
      future.cancel(true);
    }

    // abort the output buffer on the remote node; response of delete is ignored
    if (shouldSendDelete) {
      sendDelete();
    }
  }
 @Override
 public byte[] get(NamedKey key) {
   try (ResourceHolder<MemcachedClientIF> clientHolder = client.get()) {
     Future<Object> future;
     try {
       future = clientHolder.get().asyncGet(computeKeyHash(memcachedPrefix, key));
     } catch (IllegalStateException e) {
       // operation did not get queued in time (queue is full)
       errorCount.incrementAndGet();
       log.warn(e, "Unable to queue cache operation");
       return null;
     }
     try {
       byte[] bytes = (byte[]) future.get(timeout, TimeUnit.MILLISECONDS);
       if (bytes != null) {
         hitCount.incrementAndGet();
       } else {
         missCount.incrementAndGet();
       }
       return bytes == null ? null : deserializeValue(key, bytes);
     } catch (TimeoutException e) {
       timeoutCount.incrementAndGet();
       future.cancel(false);
       return null;
     } catch (InterruptedException e) {
       Thread.currentThread().interrupt();
       throw Throwables.propagate(e);
     } catch (ExecutionException e) {
       errorCount.incrementAndGet();
       log.warn(e, "Exception pulling item from cache");
       return null;
     }
   }
 }
  public void asyncCallback() {
    final Client client = ClientFactory.newClient();
    Invocation request =
        client.request("http://jaxrs.examples.org/jaxrsApplication/customers/{id}").get();
    request.pathParam("id", 123);

    // invoke a request in background
    client.queue(
        request,
        new InvocationCallback<Customer>() {

          @Override
          public void onComplete(Future<Customer> future) {
            // Do something
          }
        });

    // invoke another request in background
    Future<?> handle =
        request
            .pathParam("id", 456)
            .queue(
                new InvocationCallback<HttpResponse>() {

                  @Override
                  public void onComplete(Future<HttpResponse> future) {
                    // do something
                  }
                });
    handle.cancel(true);
  }
Exemple #20
0
  public synchronized void doDie(boolean win) {
    if (_fishAiTask != null) {
      _fishAiTask.cancel(false);
      _fishAiTask = null;
    }

    if (_fisher == null) {
      return;
    }

    if (win) {
      final L2FishingMonster fishingMonster =
          FishingMonstersData.getInstance().getFishingMonster(_fisher.getLevel());
      if (fishingMonster != null) {
        if (Rnd.get(100) <= fishingMonster.getProbability()) {
          _fisher.sendPacket(SystemMessageId.YOU_VE_CAUGHT_GOLDEEN);
          final L2Npc monster =
              AbstractScript.addSpawn(fishingMonster.getFishingMonsterId(), _fisher);
          monster.setTarget(_fisher);
        } else {
          _fisher.sendPacket(SystemMessageId.YOU_CAUGHT_SOMETHING);
          _fisher.addItem("Fishing", _fishId, 1, null, true);
          FishingChampionshipManager.getInstance().newFish(_fisher, _lureId);
        }
      }
    }

    _fisher.endFishing(win, true);
    _fisher = null;
  }
    @Override
    public Boolean call() throws Exception {
      List<Future<Boolean>> futureList = new ArrayList<>();
      List<Get> getList = new ArrayList<>(Constant.BATCH_GROUP_SIZE);
      int count = 0;
      for (Get get : gets) {
        getList.add(get);
        if (count % Constant.BATCH_GROUP_SIZE == 0) {
          Future<Boolean> f =
              AsyncThreadPoolFactory.ASYNC_HBASE_THREAD_POOL.submit(new GetTask(getList, result));
          futureList.add(f);
          getList = new ArrayList<>(Constant.BATCH_GROUP_SIZE);
        }

        count++;
      }
      Future<Boolean> f =
          AsyncThreadPoolFactory.ASYNC_HBASE_THREAD_POOL.submit(new GetTask(getList, result));
      futureList.add(f);

      boolean isOk = false;
      for (Future<Boolean> future : futureList) {
        try {
          isOk = future.get(500, TimeUnit.MILLISECONDS);
        } catch (TimeoutException ignored) {
        } catch (Exception e) {
          e.printStackTrace();
        } finally {
          if (!isOk) {
            future.cancel(Boolean.FALSE);
          }
        }
      }
      return isOk;
    }
  @Override
  protected long runQueuePass() throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    fizzBuzzQueueProcessor.reset(latch);

    Future<?>[] futures = new Future[NUM_EVENT_PROCESSORS];
    futures[0] = executor.submit(fizzQueueProcessor);
    futures[1] = executor.submit(buzzQueueProcessor);
    futures[2] = executor.submit(fizzBuzzQueueProcessor);

    long start = System.currentTimeMillis();

    for (long i = 0; i < ITERATIONS; i++) {
      Long value = Long.valueOf(i);
      fizzInputQueue.put(value);
      buzzInputQueue.put(value);
    }

    latch.await();
    long opsPerSecond = (ITERATIONS * 1000L) / (System.currentTimeMillis() - start);

    fizzQueueProcessor.halt();
    buzzQueueProcessor.halt();
    fizzBuzzQueueProcessor.halt();

    for (Future<?> future : futures) {
      future.cancel(true);
    }

    Assert.assertEquals(expectedResult, fizzBuzzQueueProcessor.getFizzBuzzCounter());

    return opsPerSecond;
  }
 /** Stops the lineage worker service. */
 public void stop() {
   if (mFilePersistenceService != null) {
     mFilePersistenceService.cancel(true);
   }
   mFileSystemMasterWorkerClient.close();
   getExecutorService().shutdown();
 }
Exemple #24
0
 boolean cancel() {
   boolean cancelled = false;
   for (JavaFutureAction<?> action : sparkJobs) {
     cancelled |= action.cancel(true);
   }
   return cancelled | (future != null && future.cancel(true));
 }
Exemple #25
0
  /** Entry point for a streaming Fizz Buzz! */
  public static void main(String[] args) throws Exception {
    Topology topology = new Topology();

    // Declare an infinite stream of Long values
    TStream<Long> counting = BeaconStreams.longBeacon(topology);

    // Throttle the rate to allow the output to be seen easier
    counting = counting.throttle(100, TimeUnit.MILLISECONDS);

    // Print the tuples to standard output
    playFizzBuzz(counting).print();

    // At this point the streaming topology (streaming) is
    // declared, but no data is flowing. The topology
    // must be submitted to a StreamsContext to be executed.

    // Since this is an streaming graph with an endless
    // data source it will run for ever
    Future<?> runningTopology = StreamsContextFactory.getEmbedded().submit(topology);

    // Run for one minute before canceling.
    Thread.sleep(TimeUnit.MINUTES.toMillis(1));

    runningTopology.cancel(true);
  }
 public void doFuture() {
   CallableTask call = new CallableTask();
   try {
     /**
      * Future<t> is result of asynchronous computation. It may possible that CallableTask has not
      * started yet but 'ExecutorService' gives the result via Future Object.
      */
     Future<String> future = executorPool.submit(call);
     /** We can check if CallableTask has been completed. */
     System.out.println("Status of Callable Task [Is Completed ? " + future.isDone() + "]");
     /**
      * We can get the result of callable Task. Note : future.get() is a blocking call, It will
      * wait until the associated process finishes.
      */
     System.out.println("Result of callable task [" + future.get() + "]");
     /** We can cancel the task. */
     System.out.println("Trying to cancel the task [Is Cancelled ? " + future.cancel(false) + "]");
     /**
      * We can see if the task was canceled. Returns true if this task was canceled before it
      * completed normally
      */
     System.out.println("Was task canceled before normal complition ? -" + future.isCancelled());
   } catch (Exception e) {
     e.printStackTrace();
   } finally {
     executorPool.shutdownNow();
   }
 }
Exemple #27
0
 /**
  * Aborts the connection in response to an error.
  *
  * @param e The error that caused the connection to be aborted. Never null.
  */
 @java.lang.SuppressWarnings("ToArrayCallWithZeroLengthArrayArgument")
 @SuppressWarnings(
     "ITA_INEFFICIENT_TO_ARRAY") // intentionally; race condition on listeners otherwise
 protected void terminate(IOException e) {
   try {
     synchronized (this) {
       if (e == null) throw new IllegalArgumentException();
       outClosed = inClosed = e;
       try {
         transport.closeRead();
       } catch (IOException x) {
         logger.log(Level.WARNING, "Failed to close down the reader side of the transport", x);
       }
       try {
         synchronized (pendingCalls) {
           for (Request<?, ?> req : pendingCalls.values()) req.abort(e);
           pendingCalls.clear();
         }
         synchronized (executingCalls) {
           for (Request<?, ?> r : executingCalls.values()) {
             java.util.concurrent.Future<?> f = r.future;
             if (f != null) f.cancel(true);
           }
           executingCalls.clear();
         }
       } finally {
         notifyAll();
       }
     } // JENKINS-14909: leave synch block
   } finally {
     if (e instanceof OrderlyShutdown) e = null;
     for (Listener l : listeners.toArray(new Listener[0])) l.onClosed(this, e);
   }
 }
 @Override
 protected void doClose() throws ElasticsearchException {
   int size = tasks.size();
   if (size > 0) {
     for (Future<?> f : tasks) {
       if (!f.isDone()) {
         logger.info("aborting knapsack task {}", f);
         boolean b = f.cancel(true);
         if (!b) {
           logger.error("knapsack task {} could not be cancelled", f);
         }
       }
     }
     tasks.clear();
   }
   logger.info("knapsack shutdown...");
   executor.shutdown();
   try {
     this.executor.awaitTermination(5, TimeUnit.SECONDS);
   } catch (InterruptedException e) {
     throw new ElasticsearchException(e.getMessage());
   }
   if (!executor.isShutdown()) {
     logger.info("knapsack shutdown now");
     executor.shutdownNow();
     try {
       this.executor.awaitTermination(5, TimeUnit.SECONDS);
     } catch (InterruptedException e) {
       throw new ElasticsearchException(e.getMessage());
     }
   }
   logger.info("knapsack shutdown complete");
 }
 public void decodePage(
     Object decodeKey,
     int pageNum,
     final DecodeCallback decodeCallback,
     float zoom,
     RectF pageSliceBounds) {
   final DecodeTask decodeTask =
       new DecodeTask(pageNum, decodeCallback, zoom, decodeKey, pageSliceBounds);
   synchronized (decodingFutures) {
     if (isRecycled) {
       return;
     }
     final Future<?> future =
         executorService.submit(
             new Runnable() {
               public void run() {
                 try {
                   Thread.currentThread().setPriority(Thread.NORM_PRIORITY - 1);
                   performDecode(decodeTask);
                 } catch (IOException e) {
                   Log.e(DECODE_SERVICE, "Decode fail", e);
                 }
               }
             });
     final Future<?> removed = decodingFutures.put(decodeKey, future);
     if (removed != null) {
       removed.cancel(false);
     }
   }
 }
Exemple #30
0
  @Override
  public Object call(
      final Method method,
      final Object[] args,
      @Nullable final AsyncMethodCallback callback,
      @Nullable final Amount<Long, Time> connectTimeoutOverride)
      throws Exception {
    try {
      Future<Object> result =
          executorService.submit(
              new Callable<Object>() {
                @Override
                public Object call() throws Exception {
                  try {
                    return invoke(method, args, callback, null, connectTimeoutOverride);
                  } catch (Throwable t) {
                    Throwables.propagateIfInstanceOf(t, Exception.class);
                    throw new RuntimeException(t);
                  }
                }
              });

      try {
        return result.get(timeout.getValue(), timeout.getUnit().getTimeUnit());
      } catch (TimeoutException e) {
        result.cancel(true);
        throw new TTimeoutException(e);
      } catch (ExecutionException e) {
        throw Throwables.propagate(e.getCause());
      }
    } catch (RejectedExecutionException e) {
      throw new TResourceExhaustedException(e);
    }
  }