Example usage for java.util.concurrent Future cancel

List of usage examples for java.util.concurrent Future cancel

Introduction

In this page you can find the example usage for java.util.concurrent Future cancel.

Prototype

boolean cancel(boolean mayInterruptIfRunning);

Source Link

Document

Attempts to cancel execution of this task.

Usage

From source file:org.apache.gobblin.scheduler.JobScheduler.java

/**
 * Schedule a job immediately./*from  w  ww .  j  a  v a  2s  .co  m*/
 *
 * <p>
 *   This method calls the Quartz scheduler to scheduler the job.
 * </p>
 *
 * @param jobProps Job configuration properties
 * @param jobListener {@link JobListener} used for callback,
 *                    can be <em>null</em> if no callback is needed.
 * @throws JobException when there is anything wrong
 *                      with scheduling the job
 */
public Future<?> scheduleJobImmediately(Properties jobProps, JobListener jobListener, JobLauncher jobLauncher) {
    Callable<Void> callable = new Callable<Void>() {
        @Override
        public Void call() throws JobException {
            try {
                runJob(jobProps, jobListener, jobLauncher);
            } catch (JobException je) {
                LOG.error("Failed to run job " + jobProps.getProperty(ConfigurationKeys.JOB_NAME_KEY), je);
                throw je;
            }
            return null;
        }
    };

    final Future<?> future = this.jobExecutor.submit(callable);
    return new Future() {
        @Override
        public boolean cancel(boolean mayInterruptIfRunning) {
            if (!cancelRequested) {
                return false;
            }
            boolean result = true;
            try {
                jobLauncher.cancelJob(jobListener);
            } catch (JobException e) {
                LOG.error("Failed to cancel job " + jobProps.getProperty(ConfigurationKeys.JOB_NAME_KEY), e);
                result = false;
            }
            if (mayInterruptIfRunning) {
                result &= future.cancel(true);
            }
            return result;
        }

        @Override
        public boolean isCancelled() {
            return future.isCancelled();
        }

        @Override
        public boolean isDone() {
            return future.isDone();
        }

        @Override
        public Object get() throws InterruptedException, ExecutionException {
            return future.get();
        }

        @Override
        public Object get(long timeout, TimeUnit unit)
                throws InterruptedException, ExecutionException, TimeoutException {
            return future.get(timeout, unit);
        }
    };
}

From source file:com.splout.db.dnode.DNodeHandler.java

@Override
public String abortDeploy(long version) throws DNodeException {
    try {//  w w  w .  j  a  v  a  2s.c o  m
        synchronized (deployLock) {
            // No new deploys to be handled until we
            // cancel the current one
            Future<?> future = deploysBeingExecuted.get(version);
            if (future == null) {
                return JSONSerDe
                        .ser(new DNodeStatusResponse("Not deployment running with version[" + version + "]"));
            }
            future.cancel(true);
            return JSONSerDe.ser(
                    new DNodeStatusResponse("status[OK]. Deploy with version[" + version + "] cancelled."));
        }
    } catch (JSONSerDeException e) {
        unexpectedException(e);
        throw new DNodeException(EXCEPTION_UNEXPECTED, e.getMessage());
    }
}

From source file:com.imaginary.home.controller.Command.java

private @Nonnull boolean[] waitFor(@Nonnull ArrayList<Future<Boolean>> threads)
        throws ControllerException, CommunicationException {
    boolean[] results = new boolean[threads.size()];
    long t = System.currentTimeMillis() + timeout;
    boolean done = true;
    int i = 0;//from ww  w  .  j  av a  2 s  .  c  o  m

    for (Future<Boolean> f : threads) {
        done = false;
        while (t > System.currentTimeMillis()) {
            try {
                if (f.isDone()) {
                    results[i++] = f.get();
                    done = true;
                    break;
                }
                try {
                    Thread.sleep(500L);
                } catch (InterruptedException ignore) {
                }
            } catch (ExecutionException e) {
                if (e.getCause() instanceof ControllerException) {
                    throw (ControllerException) e.getCause();
                } else if (e.getCause() instanceof CommunicationException) {
                    throw (CommunicationException) e.getCause();
                }
                throw new ControllerException(e);
            } catch (InterruptedException e) {
                throw new ControllerException(e);
            }
        }
        if (!done && !f.isDone()) {
            f.cancel(true);
        }
    }
    if (!done) {
        throw new ControllerException("Action timed out");
    }
    return results;
}

From source file:net.solarnetwork.node.io.serial.rxtx.SerialPortConnection.java

private <T> T performIOTaskWithMaxWait(AbortableCallable<T> task) throws IOException {
    T result = null;//from  w  ww.ja  v  a 2 s  .co  m
    Future<T> future = executor.submit(task);
    final long maxMs = Math.max(1, serialParams.getMaxWait());
    eventLog.trace("Waiting at most {}ms for data", maxMs);
    try {
        result = future.get(maxMs, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
        log.debug("Interrupted communicating with serial port", e);
        throw new IOException("Interrupted communicating with serial port", e);
    } catch (ExecutionException e) {
        log.debug("Exception thrown communicating with serial port", e.getCause());
        throw new IOException("Exception thrown communicating with serial port", e.getCause());
    } catch (TimeoutException e) {
        log.warn("Timeout waiting {}ms for serial data, aborting operation", maxMs);
        future.cancel(true);
        throw new LockTimeoutException("Timeout waiting " + serialParams.getMaxWait() + "ms for serial data");
    } finally {
        task.abort();
    }
    return result;
}

From source file:net.solarnetwork.node.io.rxtx.SerialPortSupport.java

/**
 * Handle a SerialEvent, looking for "magic" data.
 * //  ww w . j  a v  a 2s.  c o  m
 * <p>
 * <b>Note</b> that the <em>magic</em> bytes are <em>not</em> returned by
 * this method, they are stripped from the output buffer.
 * </p>
 * 
 * @param event
 *        the event
 * @param in
 *        the InputStream to read data from
 * @param sink
 *        the output buffer to store the collected bytes
 * @param magicBytes
 *        the "magic" bytes to look for in the event stream
 * @param readLength
 *        the number of bytes, excluding the magic bytes, to read from the
 *        stream
 * @return <em>true</em> if the data has been found
 * @throws TimeoutException
 *         if {@code maxWait} is configured and that amount of time passes
 *         before the requested serial data is read
 */
protected boolean handleSerialEvent(final SerialPortEvent event, final InputStream in,
        final ByteArrayOutputStream sink, final byte[] magicBytes, final int readLength)
        throws TimeoutException, InterruptedException, ExecutionException {
    if (timeout < 1) {
        return handleSerialEventWithoutTimeout(event, in, sink, magicBytes, readLength);
    }

    Callable<Boolean> task = new Callable<Boolean>() {

        @Override
        public Boolean call() throws Exception {
            return handleSerialEventWithoutTimeout(event, in, sink, magicBytes, readLength);
        }
    };
    Future<Boolean> future = executor.submit(task);
    boolean result = false;
    final long maxMs = Math.max(1, this.maxWait - System.currentTimeMillis() + timeout);
    eventLog.trace("Waiting at most {}ms for data", maxMs);
    try {
        result = future.get(maxMs, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
        log.debug("Interrupted waiting for serial data");
        throw e;
    } catch (ExecutionException e) {
        // log stack trace in DEBUG
        log.debug("Exception thrown reading from serial port", e.getCause());
        throw e;
    } catch (TimeoutException e) {
        log.warn("Timeout waiting {}ms for serial data, aborting read", maxMs);
        future.cancel(true);
        throw e;
    }
    return result;
}

From source file:net.solarnetwork.node.io.rxtx.SerialPortSupport.java

/**
 * Handle a SerialEvent, looking for "magic" start and end data markers.
 * /*from   ww  w. j  a  v  a  2 s.  c  om*/
 * <p>
 * <b>Note</b> that the <em>magic</em> bytes <em>are</em> returned by this
 * method.
 * </p>
 * 
 * @param event
 *        the event
 * @param in
 *        the InputStream to read data from
 * @param sink
 *        the output buffer to store the collected bytes
 * @param magicBytes
 *        the "magic" bytes to look for in the event stream
 * @param eofBytes
 *        the "end of file" bytes, that signals the end of the message to
 *        read
 * @return <em>true</em> if the data has been found
 * @throws TimeoutException
 *         if {@code maxWait} is configured and that amount of time passes
 *         before the requested serial data is read
 */
protected boolean handleSerialEvent(final SerialPortEvent event, final InputStream in,
        final ByteArrayOutputStream sink, final byte[] magicBytes, final byte[] eofBytes)
        throws TimeoutException, InterruptedException, ExecutionException {
    if (timeout < 1) {
        return handleSerialEventWithoutTimeout(event, in, sink, magicBytes, eofBytes);
    }

    Callable<Boolean> task = new Callable<Boolean>() {

        @Override
        public Boolean call() throws Exception {
            return handleSerialEventWithoutTimeout(event, in, sink, magicBytes, eofBytes);
        }
    };
    Future<Boolean> future = executor.submit(task);
    boolean result = false;
    final long maxMs = Math.max(1, this.maxWait - System.currentTimeMillis() + timeout);
    eventLog.trace("Waiting at most {}ms for data", maxMs);
    try {
        result = future.get(maxMs, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
        log.debug("Interrupted waiting for serial data");
        throw e;
    } catch (ExecutionException e) {
        // log stack trace in DEBUG
        log.debug("Exception thrown reading from serial port", e.getCause());
        throw e;
    } catch (TimeoutException e) {
        log.warn("Timeout waiting {}ms for serial data, aborting read", maxMs);
        future.cancel(true);
        throw e;
    }
    return result;
}

From source file:io.druid.client.cache.MemcachedCache.java

@Override
public byte[] get(NamedKey key) {
    try (ResourceHolder<MemcachedClientIF> clientHolder = client.get()) {
        Future<Object> future;
        try {/*from   w  ww .j  a  va  2 s  .  com*/
            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;
        }
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
}

From source file:org.apache.druid.client.cache.MemcachedCache.java

@Override
public byte[] get(NamedKey key) {
    try (ResourceHolder<MemcachedClientIF> clientHolder = client.get()) {
        Future<Object> future;
        try {/*from  w  w  w .ja va  2s. c  o m*/
            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;
        }
    }
}

From source file:org.apache.nifi.bootstrap.RunNiFi.java

private void handleLogging(final Process process) {
    final Set<Future<?>> existingFutures = loggingFutures;
    if (existingFutures != null) {
        for (final Future<?> future : existingFutures) {
            future.cancel(false);
        }/*from  ww  w  . j a v a2 s .  c  o m*/
    }

    final Future<?> stdOutFuture = loggingExecutor.submit(new Runnable() {
        @Override
        public void run() {
            final Logger stdOutLogger = LoggerFactory.getLogger("org.apache.nifi.StdOut");
            final InputStream in = process.getInputStream();
            try (final BufferedReader reader = new BufferedReader(new InputStreamReader(in))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    stdOutLogger.info(line);
                }
            } catch (IOException e) {
                defaultLogger.error("Failed to read from NiFi's Standard Out stream", e);
            }
        }
    });

    final Future<?> stdErrFuture = loggingExecutor.submit(new Runnable() {
        @Override
        public void run() {
            final Logger stdErrLogger = LoggerFactory.getLogger("org.apache.nifi.StdErr");
            final InputStream in = process.getErrorStream();
            try (final BufferedReader reader = new BufferedReader(new InputStreamReader(in))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    stdErrLogger.error(line);
                }
            } catch (IOException e) {
                defaultLogger.error("Failed to read from NiFi's Standard Error stream", e);
            }
        }
    });

    final Set<Future<?>> futures = new HashSet<>();
    futures.add(stdOutFuture);
    futures.add(stdErrFuture);
    this.loggingFutures = futures;
}

From source file:org.codice.ddf.catalog.sourcepoller.Poller.java

private Commitable load(final K key, final Callable<V> loader, final long timeout,
        final TimeUnit timeoutTimeUnit) {
    final Future<V> loaderFuture;
    try {/*  ww w.j  av a 2s  . c  o  m*/
        loaderFuture = pollThreadPool.submit(loader);
    } catch (final RejectedExecutionException e) {
        // the loader {@link Callable} could not be scheduled for execution
        return () -> {
            throw e;
        };
    }

    try {
        final V newValue = loaderFuture.get(timeout, timeoutTimeUnit);
        if (newValue == null) {
            return () -> {
                throw new IllegalArgumentException(
                        "Poller values may not be null, but the loaded value for " + key + " was null.");
            };
        }

        return () -> cacheNewValue(key, newValue);
    } catch (TimeoutException e) {
        LOGGER.debug("The loader for {} did not complete within {} {}. Cancelling the loader task", key,
                timeout, timeoutTimeUnit);
        loaderFuture.cancel(true);
        return () -> handleTimeout(key);
    } catch (ExecutionException e) {
        final Throwable cause = e.getCause();
        if (cause instanceof RuntimeException) {
            final RuntimeException runtimeException = (RuntimeException) cause;
            return () -> handleException(key, runtimeException);
        } else {
            return () -> {
                throw cause;
            };
        }
    } catch (CancellationException e) {
        return () -> {
            throw e;
        };
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        return () -> {
            throw e;
        };
    }
}