下面列出了java.util.concurrent.Future#cancel ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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);
}
}
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.");
}
}
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);
}
}
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;
}
}
}
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();
}
}
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;
}
}
@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());
}
/**
* 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);
}
}
}
/**
* 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();
}
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 ");
}
}
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) {}
}
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;
}
}
}
/**
* 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;
}
}
@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());
}
/**
* @param taskId
*/
public Future<?> cancelTask(TaskId taskId) {
Future<?> task = tasks.remove(taskId.ordinal());
if (task != null) {
task.cancel(false);
}
return task;
}
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"));
}
}
/**
* Cancel all remaining tasks.
*/
public void cancelAllTasks() {
for (Future<T> future : mFutureSet) {
future.cancel(true /*mayInterruptIfRunning*/);
}
}
@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();
}
}
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();
}
@Override
public boolean stop(String entityClassName) {
Future<?> future = this.inFlightTasksMap.get(entityClassName);
return future != null && future.cancel(true);
}