List of usage examples for java.util.concurrent Future cancel
boolean cancel(boolean mayInterruptIfRunning);
From source file:org.cleverbus.component.externalcall.ExternalCallComponentTest.java
private Future<String> getStringBodyFuture(final Future<Exchange> reply) { return new Future<String>() { @Override/*from w w w . j av a2 s . c o m*/ public boolean cancel(boolean mayInterruptIfRunning) { return reply.cancel(mayInterruptIfRunning); } @Override public boolean isCancelled() { return reply.isCancelled(); } @Override public boolean isDone() { return reply.isDone(); } @Override public String get() throws InterruptedException, ExecutionException { return getReplyString(reply.get()); } @Override public String get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return getReplyString(reply.get(timeout, unit)); } private String getReplyString(Exchange exchange) throws InterruptedException, ExecutionException { throwExceptionOptionally(exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class)); throwExceptionOptionally(exchange.getException()); return exchange.getOut().getBody(String.class); } private void throwExceptionOptionally(Exception exc) throws InterruptedException, ExecutionException { if (exc != null) { if (exc instanceof InterruptedException) { throw (InterruptedException) exc; } else if (exc instanceof ExecutionException) { throw (ExecutionException) exc; } else { throw new ExecutionException(exc); } } } }; }
From source file:org.onebusaway.nyc.vehicle_tracking.impl.VehicleLocationSimulationServiceImpl.java
@Override public void cancelSimulation(int taskId) { final SimulatorTask task = _tasks.remove(taskId); if (task != null) { final Future<?> future = task.getFuture(); future.cancel(true); task.resetAllVehiclesAppearingInRecordData(); for (final Object tag : task.getTags()) { final List<SimulatorTask> list = getTasksForTag(tag, false); if (list != null) { synchronized (list) { list.remove(task);//ww w.j a va 2 s. c o m } } } } }
From source file:org.apache.hadoop.hbase.procedure.ProcedureMember.java
/** * Submit an subprocedure for execution. This starts the local acquire phase. * @param subproc the subprocedure to execute. * @return <tt>true</tt> if the subprocedure was started correctly, <tt>false</tt> if it * could not be started. In the latter case, the subprocedure holds a reference to * the exception that caused the failure. *///from ww w . ja v a2 s.c o m public boolean submitSubprocedure(Subprocedure subproc) { // if the submitted subprocedure was null, bail. if (subproc == null) { LOG.warn("Submitted null subprocedure, nothing to run here."); return false; } String procName = subproc.getName(); if (procName == null || procName.length() == 0) { LOG.error("Subproc name cannot be null or the empty string"); return false; } // make sure we aren't already running an subprocedure of that name Subprocedure rsub; synchronized (subprocs) { rsub = subprocs.get(procName); } if (rsub != null) { if (!rsub.isComplete()) { LOG.error("Subproc '" + procName + "' is already running. Bailing out"); return false; } LOG.warn("A completed old subproc " + procName + " is still present, removing"); subprocs.remove(procName); } LOG.debug("Submitting new Subprocedure:" + procName); // kick off the subprocedure Future<Void> future = null; try { synchronized (subprocs) { subprocs.put(procName, subproc); } future = this.pool.submit(subproc); return true; } catch (RejectedExecutionException e) { synchronized (subprocs) { subprocs.remove(procName); } // the thread pool is full and we can't run the subprocedure String msg = "Subprocedure pool is full!"; subproc.cancel(msg, e.getCause()); // cancel all subprocedures proactively if (future != null) { future.cancel(true); } } LOG.error("Failed to start subprocedure '" + procName + "'"); return false; }
From source file:fr.duminy.jbackup.core.JBackupImplTest.java
@Test public void testBackup_withCancellable() throws Throwable { // prepare test final BackupConfiguration config = createConfiguration(); final MutableBoolean taskStarted = new MutableBoolean(false); final Task mockBackupTask = createAlwaysWaitingTask(Task.class, taskStarted); final MutableObject<Cancellable> actualCancellable = new MutableObject<>(); final MutableObject<TaskListener> actualListener = new MutableObject<>(); JBackupImpl jBackup = spy(new JBackupImpl() { @Override/*www . ja va2 s. c om*/ Task createBackupTask(BackupConfiguration config, TaskListener listener, Cancellable cancellable) { actualListener.setValue(listener); actualCancellable.setValue(cancellable); return mockBackupTask; } }); // test try { Future<Void> future = jBackup.backup(config); // wait task is actually started waitTaskStarted(taskStarted, actualCancellable); assertThat(actualCancellable.getValue()).as("cancellable").isNotNull(); assertThat(actualCancellable.getValue().isCancelled()).as("cancelled").isFalse(); future.cancel(true); assertThat(actualCancellable.getValue().isCancelled()).as("cancelled").isTrue(); } finally { jBackup.shutdown(null); } // assertions InOrder inOrder = inOrder(mockBackupTask, jBackup); inOrder.verify(jBackup, times(1)).backup(eq(config)); // called above inOrder.verify(jBackup, times(1)).createBackupTask(eq(config), eq(actualListener.getValue()), eq(actualCancellable.getValue())); inOrder.verify(mockBackupTask, times(1)).call(); inOrder.verify(jBackup, times(1)).shutdown(isNull(TerminationListener.class)); // called above inOrder.verifyNoMoreInteractions(); }
From source file:org.apache.camel.impl.DefaultShutdownStrategy.java
protected boolean doShutdown(CamelContext context, List<RouteStartupOrder> routes, long timeout, TimeUnit timeUnit, boolean suspendOnly, boolean abortAfterTimeout) throws Exception { StopWatch watch = new StopWatch(); // at first sort according to route startup order List<RouteStartupOrder> routesOrdered = new ArrayList<RouteStartupOrder>(routes); Collections.sort(routesOrdered, new Comparator<RouteStartupOrder>() { public int compare(RouteStartupOrder o1, RouteStartupOrder o2) { return o1.getStartupOrder() - o2.getStartupOrder(); }// w w w.j ava 2s . c o m }); if (shutdownRoutesInReverseOrder) { Collections.reverse(routesOrdered); } if (timeout > 0) { LOG.info("Starting to graceful shutdown " + routesOrdered.size() + " routes (timeout " + timeout + " " + timeUnit.toString().toLowerCase() + ")"); } else { LOG.info("Starting to graceful shutdown " + routesOrdered.size() + " routes (no timeout)"); } // use another thread to perform the shutdowns so we can support timeout Future future = getExecutorService() .submit(new ShutdownTask(context, routesOrdered, suspendOnly, abortAfterTimeout)); try { if (timeout > 0) { future.get(timeout, timeUnit); } else { future.get(); } } catch (TimeoutException e) { // timeout then cancel the task future.cancel(true); // if set, stop processing and return false to indicate that the shutdown is aborting if (abortAfterTimeout) { LOG.warn("Timeout occurred. Aborting the shutdown now."); return false; } else { if (shutdownNowOnTimeout) { LOG.warn("Timeout occurred. Now forcing the routes to be shutdown now."); // force the routes to shutdown now shutdownRoutesNow(routesOrdered); } else { LOG.warn("Timeout occurred. Will ignore shutting down the remainder routes."); } } } catch (ExecutionException e) { // unwrap execution exception throw ObjectHelper.wrapRuntimeCamelException(e.getCause()); } // convert to seconds as its easier to read than a big milli seconds number long seconds = TimeUnit.SECONDS.convert(watch.stop(), TimeUnit.MILLISECONDS); LOG.info("Graceful shutdown of " + routesOrdered.size() + " routes completed in " + seconds + " seconds"); return true; }
From source file:nl.nn.adapterframework.core.TimeoutGuardSenderWithParametersBase.java
public String sendMessage(String correlationID, String message, ParameterResolutionContext prc) throws SenderException, TimeOutException { SendMessage sendMessage = new SendMessage(correlationID, message, prc, Thread.currentThread().getName(), NDC.peek());// www .j ava2 s . c om ExecutorService service = Executors.newSingleThreadExecutor(); Future<String> future = service.submit(sendMessage); String result = null; try { log.debug(getLogPrefix() + "setting timeout of [" + retrieveTymeout() + "] s"); result = (String) future.get(retrieveTymeout(), TimeUnit.SECONDS); if (StringUtils.isNotEmpty(getXmlTag())) { result = "<" + getXmlTag() + "><![CDATA[" + result + "]]></" + getXmlTag() + ">"; } } catch (Exception e) { boolean timedOut = false; Throwable t = e.getCause(); String msg; if (e instanceof TimeoutException) { String errorMsg = getLogPrefix() + "exceeds timeout of [" + retrieveTymeout() + "] s, interupting"; future.cancel(true); msg = (t != null ? t.getClass().getName() : e.getClass().getName()) + ": " + errorMsg; timedOut = true; } else { msg = (t != null ? t.getClass().getName() : e.getClass().getName()); if (t != null && t instanceof TimeOutException) { timedOut = true; } } if (isThrowException()) { if (timedOut) { throw new TimeOutException(msg, (t != null ? t : e)); } else { throw new SenderException(msg, (t != null ? t : e)); } } else { String msgString = msg + ": " + e.getMessage(); log.error(msgString); String msgCdataString = "<![CDATA[" + msgString + "]]>"; result = "<error>" + msgCdataString + "</error>"; } } finally { service.shutdown(); } return result; }
From source file:com.alibaba.otter.shared.communication.core.impl.DefaultCommunicationClientImpl.java
public Object call(final String[] addrs, final Event event) { Assert.notNull(this.factory, "No factory specified"); if (addrs == null || addrs.length == 0) { throw new IllegalArgumentException("addrs example: 127.0.0.1:1099"); }/*from www . j a v a 2 s . c o m*/ ExecutorCompletionService completionService = new ExecutorCompletionService(executor); List<Future<Object>> futures = new ArrayList<Future<Object>>(addrs.length); List result = new ArrayList(10); for (final String addr : addrs) { futures.add(completionService.submit((new Callable<Object>() { @Override public Object call() throws Exception { return DefaultCommunicationClientImpl.this.call(addr, event); } }))); } Exception ex = null; int errorIndex = 0; while (errorIndex < futures.size()) { try { Future future = completionService.take();// ? future.get(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); ex = e; break; } catch (ExecutionException e) { ex = e; break; } errorIndex++; } if (errorIndex < futures.size()) { for (int index = 0; index < futures.size(); index++) { Future<Object> future = futures.get(index); if (future.isDone() == false) { future.cancel(true); } } } else { for (int index = 0; index < futures.size(); index++) { Future<Object> future = futures.get(index); try { result.add(future.get()); } catch (InterruptedException e) { // ignore Thread.currentThread().interrupt(); } catch (ExecutionException e) { // ignore } } } if (ex != null) { throw new CommunicationException( String.format("call addr[%s] error by %s", addrs[errorIndex], ex.getMessage()), ex); } else { return result; } }
From source file:fr.duminy.jbackup.core.JBackupImplTest.java
@Test public void testRestore_withCancellable() throws Throwable { // prepare test final Path archive = tempFolder.newFolder().toPath().resolve("archive.zip"); final Path targetDirectory = tempFolder.newFolder().toPath(); final BackupConfiguration config = createConfiguration(); final MutableBoolean taskStarted = new MutableBoolean(false); final Task mockRestoreTask = createAlwaysWaitingTask(Task.class, taskStarted); final MutableObject<Cancellable> actualCancellable = new MutableObject<>(); final MutableObject<TaskListener> actualListener = new MutableObject<>(); JBackupImpl jBackup = spy(new JBackupImpl() { @Override/*from w w w .j a va2 s .com*/ Task createRestoreTask(BackupConfiguration config, Path archive, Path targetDirectory, TaskListener listener, Cancellable cancellable) { actualListener.setValue(listener); actualCancellable.setValue(cancellable); return mockRestoreTask; } }); // test try { Future<Void> future = jBackup.restore(config, archive, targetDirectory); // wait task is actually started waitTaskStarted(taskStarted, actualCancellable); assertThat(actualCancellable.getValue()).as("cancellable").isNotNull(); assertThat(actualCancellable.getValue().isCancelled()).as("cancelled").isFalse(); future.cancel(true); assertThat(actualCancellable.getValue().isCancelled()).as("cancelled").isTrue(); } finally { jBackup.shutdown(null); } // assertions InOrder inOrder = inOrder(mockRestoreTask, jBackup); inOrder.verify(jBackup, times(1)).restore(eq(config), eq(archive), eq(targetDirectory)); // called above inOrder.verify(jBackup, times(1)).createRestoreTask(eq(config), eq(archive), eq(targetDirectory), eq(actualListener.getValue()), eq(actualCancellable.getValue())); inOrder.verify(mockRestoreTask, times(1)).call(); inOrder.verify(jBackup, times(1)).shutdown(isNull(TerminationListener.class)); // called above inOrder.verifyNoMoreInteractions(); }
From source file:com.eucalyptus.storage.ISCSIManager.java
/** * Executes the specified command in a separate process. A {@link DirectStorageInfo#timeoutInMillis timeout} is enforced on the process using * {@link java.util.concurrent.ExecutorService ExecutorService} framework. If the process does not complete with in the timeout, it is cancelled. * //from w ww. ja va2 s. co m * @param command * @param timeout * @return CommandOutput * @throws EucalyptusCloudException */ private CommandOutput execute(String[] command, Long timeout) throws EucalyptusCloudException { try { Integer returnValue = -999999; Runtime runtime = Runtime.getRuntime(); Process process = runtime.exec(command); StreamConsumer error = new StreamConsumer(process.getErrorStream()); StreamConsumer output = new StreamConsumer(process.getInputStream()); error.start(); output.start(); Callable<Integer> processMonitor = new ProcessMonitor(process); Future<Integer> processController = service.submit(processMonitor); try { returnValue = processController.get(timeout, TimeUnit.MILLISECONDS); } catch (TimeoutException tex) { String commandStr = buildCommand(command); LOG.error(commandStr + " timed out. Cancelling the process, logging a fault and exceptioning out"); processController.cancel(true); Faults.forComponent(Storage.class).havingId(TGT_HOSED).withVar("component", "Storage Controller") .withVar("timeout", Long.toString(timeout)).log(); throw new EucalyptusCloudException("No response from the command " + commandStr + ". Process timed out after waiting for " + timeout + " milliseconds"); } output.join(); error.join(); LOG.debug("ISCSIManager executed: " + JOINER.join(command) + "\n return=" + returnValue + "\n stdout=" + output.getReturnValue() + "\n stderr=" + error.getReturnValue()); return new CommandOutput(returnValue, output.getReturnValue(), error.getReturnValue()); } catch (Exception ex) { if (ex instanceof EucalyptusCloudException) { throw (EucalyptusCloudException) ex; } else { throw new EucalyptusCloudException(ex); } } }
From source file:fr.duminy.jbackup.swing.ProgressPanel.java
public void setTask(final Future<?> task) { this.task = task; if ((task != null) && (cancelButton == null)) { Utils.runInEventDispatchThread(new Runnable() { @Override/*from w w w . ja va 2 s.c o m*/ public void run() { ImageIcon icon = new ImageIcon(ProgressPanel.class.getResource("cancel.png")); cancelButton = new JButton(icon); cancelButton.setMargin(new Insets(0, 0, 0, 0)); cancelButton.setToolTipText(Bundle.getBundle(Messages.class).cancelTaskTooltip()); add(cancelButton, BorderLayout.EAST); revalidate(); cancelButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (task.cancel(false)) { removeFromParent(); } } }); } }); } }