Java Code Examples for java.util.concurrent.Future#cancel()

The following examples show how to use java.util.concurrent.Future#cancel() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ForkJoinIndexer.java    From jkes with Apache License 2.0 6 votes vote down vote up
@Override
public void start(String entityClassName) {
    synchronized (this) {
        IndexTask<?> task = this.tasksMap.get(entityClassName);

        Future<?> future = this.inFlightTasksMap.get(entityClassName);
        if(future != null && !future.isDone()) {
            if(future.cancel(true))
                logger.info("Canceled task: " + task);
        }

        Future<?> submit = submit(task);
        logger.debug("submitted task: " + task);

        Class<?> domainClass = task.getDomainClass();
        super.progress.put(domainClass.getCanonicalName(), new IndexProgress(domainClass, task.count(), (long) 0));

        this.inFlightTasksMap.put(task.getDomainClass().getCanonicalName(), submit);
    }
}
 
Example 2
Source File: Chapter07Concurrency03.java    From Java-9-Cookbook with MIT License 6 votes vote down vote up
private static void shutdownAndCancelTask(ExecutorService execService, int shutdownDelaySec, String name, Future future) {
    try {
        execService.shutdown();
        System.out.println("Waiting for " + shutdownDelaySec + " sec before shutting down service...");
        execService.awaitTermination(shutdownDelaySec, TimeUnit.SECONDS);
    } catch (Exception ex) {
        System.out.println("Caught around execService.awaitTermination(): " + ex.getClass().getName());
    } finally {
        if (!execService.isTerminated()) {
            System.out.println("Terminating remaining running tasks...");
            if (future != null && !future.isDone() && !future.isCancelled()) {
                System.out.println("Cancelling task " + name + "...");
                future.cancel(true);
            }
        }
        System.out.println("Calling execService.shutdownNow()...");
        List<Runnable> l = execService.shutdownNow();
        System.out.println(l.size() + " tasks were waiting to be executed. Service stopped.");
    }
}
 
Example 3
Source File: ByteStreamUploader.java    From bazel-buildfarm with Apache License 2.0 6 votes vote down vote up
/**
 * Cancels all running uploads. The method returns immediately and does NOT wait for the uploads
 * to be cancelled.
 *
 * <p>This method must be the last method called.
 */
public void shutdown() {
  synchronized (lock) {
    if (isShutdown) {
      return;
    }
    isShutdown = true;
    // Before cancelling, copy the futures to a separate list in order to avoid concurrently
    // iterating over and modifying the map (cancel triggers a listener that removes the entry
    // from the map. the listener is executed in the same thread.).
    List<Future<Void>> uploadsToCancel = Lists.newArrayList(uploadsInProgress.values());
    for (Future<Void> upload : uploadsToCancel) {
      upload.cancel(true);
    }
  }
}
 
Example 4
Source File: TestBase.java    From snowflake-kafka-connector with Apache License 2.0 6 votes vote down vote up
protected void test()
{
  Utils.startConnector(getTestCase().getFormat());
  ExecutorService executor = Executors.newSingleThreadExecutor();
  Future<Boolean> task = executor.submit(() ->
  {
    while (!checkResult())
    {
      Thread.sleep(SLEEP_TIME);
    }
    return true;
  });

  try
  {
    task.get(TIME_OUT_SEC, TimeUnit.SECONDS);
  } catch (Exception e)
  {
    task.cancel(true);
    e.printStackTrace();
    System.exit(1);
  }

}
 
Example 5
Source File: HsmsSsSendReplyManager.java    From secs4java8 with Apache License 2.0 6 votes vote down vote up
private void send(AsynchronousSocketChannel channel, ByteBuffer buffer)
		throws ExecutionException, HsmsSsDetectTerminateException, InterruptedException {
	
	while ( buffer.hasRemaining() ) {
		
		Future<Integer> f = channel.write(buffer);
		
		try {
			int w = f.get().intValue();
			
			if ( w <= 0 ) {
				throw new HsmsSsDetectTerminateException();
			}
		}
		catch ( InterruptedException e ) {
			f.cancel(true);
			throw e;
		}
	}
}
 
Example 6
Source File: GrpcClient.java    From etcd-java with Apache License 2.0 6 votes vote down vote up
public static <T> T waitFor(Future<T> fut, long timeoutMillis) {
    try {
        return timeoutMillis < 0L ? fut.get() : fut.get(timeoutMillis, MILLISECONDS);
    } catch (InterruptedException|CancellationException e) {
        fut.cancel(true);
        if (e instanceof InterruptedException) {
            Thread.currentThread().interrupt();
        }
        throw Status.CANCELLED.withCause(e).asRuntimeException();
    } catch (ExecutionException ee) {
        throw Status.fromThrowable(ee.getCause()).asRuntimeException();
    } catch (TimeoutException te) {
        fut.cancel(true);
        throw Status.DEADLINE_EXCEEDED.withCause(te)
            .withDescription("local timeout of " + timeoutMillis + "ms exceeded")
            .asRuntimeException();
    } catch (RuntimeException rte) {
        fut.cancel(true);
        throw Status.fromThrowable(rte).asRuntimeException();
    }
}
 
Example 7
Source File: AsyncScriptRunner.java    From sailfish-core with Apache License 2.0 6 votes vote down vote up
private void  stopScripts(Map<Long, Future<Exception>> runningScriptMap) throws InterruptedException {
	boolean localShutdown = shutdown;

	for (Entry<Long, Future<Exception>> scriptFeature : runningScriptMap.entrySet()) {
		Long scriptId = scriptFeature.getKey();

		TestScriptDescription description = testScripts.get(scriptId);
		if (localShutdown || (description != null && description.isSetCancelFlag())) {
			logger.warn("Shutdown script {}", scriptId);
			Future<Exception> future = scriptFeature.getValue();

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

	if (localShutdown) {
		shutdown = false;
	}
}
 
Example 8
Source File: AbstractClientServiceTest.java    From sofa-jraft with Apache License 2.0 6 votes vote down vote up
@Test
public void testCancel() throws Exception {
    ArgumentCaptor<InvokeCallback> callbackArg = ArgumentCaptor.forClass(InvokeCallback.class);
    PingRequest request = TestUtils.createPingRequest();

    MockRpcResponseClosure<ErrorResponse> done = new MockRpcResponseClosure<>();
    Future<Message> future = this.clientService.invokeWithDone(this.endpoint, request, done, -1);
    Mockito.verify(this.rpcClient).invokeAsync(eq(this.endpoint), eq(request), Mockito.any(),
        callbackArg.capture(), eq((long) this.rpcOptions.getRpcDefaultTimeout()));
    InvokeCallback cb = callbackArg.getValue();
    assertNotNull(cb);
    assertNotNull(future);

    assertNull(done.getResponse());
    assertNull(done.status);
    assertFalse(future.isDone());

    future.cancel(true);
    ErrorResponse response = (ErrorResponse) this.rpcResponseFactory.newResponse(null, Status.OK());
    cb.complete(response, null);

    // The closure should be notified with ECANCELED error code.
    done.latch.await();
    assertNotNull(done.status);
    assertEquals(RaftError.ECANCELED.getNumber(), done.status.getCode());
}
 
Example 9
Source File: CreatureController.java    From aion-germany with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Cancel all tasks associated with this controller (when deleting object)
 */
public void cancelAllTasks() {
	for (int i : tasks.keySet()) {
		Future<?> task = tasks.get(i);
		if (task != null && i != TaskId.RESPAWN.ordinal()) {
			task.cancel(false);
		}
	}
	tasks.clear();
}
 
Example 10
Source File: TotoroChannel.java    From canal-elasticsearch with Apache License 2.0 5 votes vote down vote up
public void putFuture(Future<ElasticsearchMetadata> future) throws InterruptedException {
    if (rollBack.state() == true) {
        transFormFuture.put(future);
    } else {
        future.cancel(true);
        logger.info("The rollback happened =============>  try cancel future ");
    }
}
 
Example 11
Source File: CreatureController.java    From aion-germany with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @param taskId
 */
public Future<?> cancelTask(TaskId taskId) {
	Future<?> task = tasks.remove(taskId.ordinal());
	if (task != null) {
		task.cancel(false);
	}
	return task;
}
 
Example 12
Source File: RequestProcessor180386Test.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testCannotScheduleLongerThanIntegerMaxValue() throws Exception {
    Runnable r = new Runnable() {

        @Override
        public void run() {
            fail ("Should not have been run");
        }
    };
    try {
        Future<?> f = RequestProcessor.getDefault().schedule(r, Long.MAX_VALUE, TimeUnit.DAYS);
        f.cancel(true);
    } catch (Exception e) {}
}
 
Example 13
Source File: MultiWindowOnDurationOp.java    From smallrye-mutiny with Apache License 2.0 5 votes vote down vote up
boolean replace(Future<?> task) {
    for (;;) {
        Future current = container.get();
        if (current == NONE) {
            if (task != null) {
                task.cancel(true);
            }
            return false;
        }
        if (container.compareAndSet(current, task)) {
            return true;
        }
    }
}
 
Example 14
Source File: AbstractAsyncHttpRequestFactoryTestCase.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void cancel() throws Exception {
	URI uri = new URI(baseUrl + "/status/notfound");
	AsyncClientHttpRequest request = this.factory.createAsyncRequest(uri, HttpMethod.GET);
	Future<ClientHttpResponse> futureResponse = request.executeAsync();
	futureResponse.cancel(true);
	assertTrue(futureResponse.isCancelled());
}
 
Example 15
Source File: XBeeFrameHandler.java    From com.zsmartsystems.zigbee with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Wait for the requested {@link XBeeEvent} to occur
 *
 * @param eventClass the {@link XBeeEvent} to wait for
 * @return the {@link XBeeEvent} once received, or null on exception
 */
public XBeeEvent eventWait(final Class<?> eventClass) {
    Future<XBeeEvent> future = waitEventAsync(eventClass);
    try {
        return future.get(commandTimeout, TimeUnit.MILLISECONDS);
    } catch (InterruptedException | ExecutionException | TimeoutException e) {
        logger.debug("XBee interrupted in eventWait {}", eventClass);
        future.cancel(true);
        return null;
    }
}
 
Example 16
Source File: ForkJoinIndexer.java    From jkes with Apache License 2.0 4 votes vote down vote up
@Override
public boolean stop(String entityClassName) {
    Future<?> future = this.inFlightTasksMap.get(entityClassName);
    return future != null && future.cancel(true);
}
 
Example 17
Source File: DatawaveFieldIndexCachingIteratorJexl.java    From datawave with Apache License 2.0 4 votes vote down vote up
private void fillSortedSets() throws IOException {
    String sourceRow = this.fiRow.toString();
    setupRowBasedHdfsBackedSet(sourceRow);
    
    // if keys is not null, then we already had a completed set which was loaded in setupRowBasedHdfsBackedSet
    if (keys != null) {
        moveToNextRow();
        return;
    }
    
    // for each range, fork off a runnable
    List<Future<?>> futures = new ArrayList<>(boundingFiRanges.size());
    if (log.isDebugEnabled()) {
        log.debug("Processing " + boundingFiRanges + " for " + this);
    }
    
    TotalResults totalResults = new TotalResults(maxResults);
    
    for (Range range : boundingFiRanges) {
        if (log.isTraceEnabled()) {
            log.trace("range -> " + range);
        }
        futures.add(fillSet(range, totalResults));
    }
    
    boolean failed = false;
    Exception exception = null;
    Object result = null;
    
    // wait for all of the threads to complete
    for (Future<?> future : futures) {
        checkTiming();
        
        if (failed || this.setControl.isCancelledQuery()) {
            future.cancel(false);
        } else {
            try {
                result = future.get();
            } catch (Exception e) {
                exception = e;
                result = e;
            }
            if (result != null) {
                failed = true;
                this.setControl.setCancelled();
            }
        }
        if (this.setControl.isCancelledQuery()) {
            break;
        }
    }
    
    if (failed) {
        log.error("Failed to complete ivarator cache: " + result, exception);
        throw new IvaratorException("Failed to complete ivarator cache: " + result, exception);
    }
    
    // now reset the current source to the next viable range
    moveToNextRow();
}
 
Example 18
Source File: RequestProcessor180386Test.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@RandomlyFails // NB-Core-Build #8322: hung
    public void testScheduleRepeatingIntervalsAreRoughlyCorrect() throws Exception {
        int runCount = 5;
        final CountDownLatch latch = new CountDownLatch(runCount);
        final List<Long> intervals = Collections.synchronizedList(new ArrayList<Long> (runCount));
//        long initialDelay = 30000;
//        long period = 20000;
//        long fudgeFactor = 4000;
        long initialDelay = 3000;
        long period = 2000;
        long fudgeFactor = 400;
        long expectedInitialDelay = initialDelay - fudgeFactor;
        long expectedPeriod = period - fudgeFactor;
        class C implements Runnable {
            volatile long start = System.currentTimeMillis();
            private int runCount;
            @Override
            public void run() {
                runCount++;
                try {
                    synchronized(this) {
                        long end = System.currentTimeMillis();
                        intervals.add (end - start);
                        start = end;
                    }
                } finally {
                    latch.countDown();
                }
            }
        }
        C c = new C();
        RequestProcessor rp = new RequestProcessor ("testScheduleRepeating", 5, true);
        try {
            Future<?> f = rp.scheduleWithFixedDelay(c, initialDelay, period, TimeUnit.MILLISECONDS);
    //        latch.await(initialDelay + fudgeFactor + ((runCount - 1) * (period + fudgeFactor)), TimeUnit.MILLISECONDS); //XXX
            latch.await();
            f.cancel(true);
            for (int i= 0; i < Math.min(runCount, intervals.size()); i++) {
                long expect = i == 0 ? expectedInitialDelay : expectedPeriod;
                assertTrue ("Expected at least " + expect + " milliseconds before run " + i + " but was " + intervals.get(i), intervals.get(i) >= expect);
            }
            //Ensure we have really exited
            try {
                f.get();
                fail ("CancellationException should have been thrown");
            } catch (CancellationException e) {}
            assertTrue(f.isCancelled());
            assertTrue(f.isDone());
        } finally {
            rp.stop();
        }
    }
 
Example 19
Source File: WaitableExecutor.java    From javaide with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Cancel all remaining tasks.
 */
public void cancelAllTasks() {
    for (Future<T> future : mFutureSet) {
        future.cancel(true /*mayInterruptIfRunning*/);
    }
}
 
Example 20
Source File: DatabaseUtils.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public static Connection connect(final String url, String user, String password, long timeToWait)
        throws DatabaseException, TimeoutException {
    final Driver theDriver = getDriver();

    final Properties props = new Properties();
    props.put("user", user);

    if (password != null) {
        props.put("password", password);
    }

    ExecutorService executor = Executors.newSingleThreadExecutor();
    Future<Connection> future = executor.submit(new Callable<Connection>() {
        public Connection call() throws Exception {
            props.put("connectTimeout", MySQLOptions.getDefault().getConnectTimeout());

            try {
                return theDriver.connect(url, props);
            } catch (SQLException sqle) {
                if (DatabaseUtils.isCommunicationsException(sqle)) {
                    // On a communications failure (e.g. the server's not running)
                    // the message horribly includes the entire stack trace of the
                    // exception chain.  We don't want to display this to our users,
                    // so let's provide our own message...
                    //
                    // If other MySQL exceptions exhibit this behavior we'll have to
                    // address this in a more general way...
                    String msg = Utils.getMessage("ERR_MySQLCommunicationFailure");

                    DatabaseException dbe = new DatabaseException(msg);
                    dbe.initCause(sqle);
                    throw dbe;
                } else {
                    throw new DatabaseException(sqle);
                }
            }
        }
    });

    try {
        return future.get(timeToWait, TimeUnit.MILLISECONDS);
    } catch (InterruptedException ie) {
        Thread.currentThread().interrupt();
        throw new DatabaseException(ie);
    } catch (ExecutionException e) {
        if (e.getCause() instanceof DatabaseException) {
            throw new DatabaseException(e.getCause());
        } else {
            throw Utils.launderThrowable(e.getCause());
        }
    } catch (TimeoutException te) {
        future.cancel(true);
        throw new TimeoutException(NbBundle.getMessage(DatabaseUtils.class, "MSG_ConnectTimedOut"));
    }
}