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.nifi.minifi.bootstrap.RunMiNiFi.java

private void handleLogging(final Process process) {
    final Set<Future<?>> existingFutures = loggingFutures;
    if (existingFutures != null) {
        for (final Future<?> future : existingFutures) {
            future.cancel(false);
        }//from  w  w w  .  j  ava2s  .  c om
    }

    final Future<?> stdOutFuture = loggingExecutor.submit(new Runnable() {
        @Override
        public void run() {
            final Logger stdOutLogger = LoggerFactory.getLogger("org.apache.nifi.minifi.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 MiNiFi's Standard Out stream", e);
            }
        }
    });

    final Future<?> stdErrFuture = loggingExecutor.submit(new Runnable() {
        @Override
        public void run() {
            final Logger stdErrLogger = LoggerFactory.getLogger("org.apache.nifi.minifi.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 MiNiFi's Standard Error stream", e);
            }
        }
    });

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

From source file:org.apache.hadoop.yarn.server.nodemanager.containermanager.ContainerManagerImpl.java

private void scheduleJWTUpdater(CMgrUpdateJWTEvent event) {
    LOG.debug("Scheduling JWT updater for container " + event.getContainerId());
    Future previousTask = removeJWTUpdaterTask(event.getContainerId());
    if (previousTask != null) {
        previousTask.cancel(true);
    }/*from   w w  w  . j a  v a2s .c o  m*/
    ContainerImpl container = (ContainerImpl) context.getContainers().get(event.getContainerId());
    if (container != null) {
        ContainerJWTUpdaterTask updaterTask = new ContainerJWTUpdaterTask(container, event.getJwt(),
                event.getJwtExpiration());
        scheduleJWTUpdaterTaskInternal(updaterTask, container.getContainerId());
    }
}

From source file:org.apache.hadoop.yarn.server.nodemanager.containermanager.ContainerManagerImpl.java

private void scheduleX509Updater(CMgrUpdateX509Event event) {
    LOG.debug("Scheduling X.509 updater for container " + event.getContainerId());
    Future previousTask = removeX509UpdaterTask(event.getContainerId());
    if (previousTask != null) {
        previousTask.cancel(true);
    }/*  w  w  w.j a  v  a2s .com*/
    ContainerImpl container = (ContainerImpl) context.getContainers().get(event.getContainerId());
    if (container != null) {
        ContainerX509UpdaterTask updaterTask = new ContainerX509UpdaterTask(container, event.getKeyStore(),
                event.getKeyStorePassword(), event.getTrustStore(), event.getTrustStorePassword(),
                event.getVersion());
        scheduleX509UpdaterTaskInternal(updaterTask, container.getContainerId());
    }
}

From source file:fr.bmartel.speedtest.SpeedTestTask.java

/**
 * write and flush mSocket./*from   w  w  w .  j  a  v a  2  s . c o  m*/
 *
 * @param data payload to write
 * @return error status (-1 for error)
 * @throws IOException mSocket io exception
 */
private int writeFlushSocket(final byte[] data) throws IOException {

    final ExecutorService executor = Executors.newSingleThreadExecutor();

    @SuppressWarnings("unchecked")
    final Future<Integer> future = executor.submit(new Callable() {

        /**
         * execute sequential write/flush task.
         *
         * @return status
         */
        public Integer call() {
            try {
                mSocket.getOutputStream().write(data);
                mSocket.getOutputStream().flush();
            } catch (IOException e) {
                return -1;
            }
            return 0;
        }
    });
    int status;
    try {
        status = future.get(mSocketInterface.getSocketTimeout(), TimeUnit.MILLISECONDS);
    } catch (TimeoutException e) {
        future.cancel(true);
        status = -1;
    } catch (InterruptedException | ExecutionException e) {
        status = -1;
    }
    executor.shutdownNow();
    return status;
}

From source file:org.apache.flume.api.NettyAvroRpcClient.java

private void append(Event event, long timeout, TimeUnit tu) throws EventDeliveryException {

    assertReady();//from   w w w.  j av a 2 s  .  c  o m

    final CallFuture<Status> callFuture = new CallFuture<Status>();

    final AvroFlumeEvent avroEvent = new AvroFlumeEvent();
    avroEvent.setBody(ByteBuffer.wrap(event.getBody()));
    avroEvent.setHeaders(toCharSeqMap(event.getHeaders()));

    Future<Void> handshake;
    try {
        // due to AVRO-1122, avroClient.append() may block
        handshake = callTimeoutPool.submit(new Callable<Void>() {

            @Override
            public Void call() throws Exception {
                avroClient.append(avroEvent, callFuture);
                return null;
            }
        });
    } catch (RejectedExecutionException ex) {
        throw new EventDeliveryException(this + ": Executor error", ex);
    }

    try {
        handshake.get(connectTimeout, TimeUnit.MILLISECONDS);
    } catch (TimeoutException ex) {
        throw new EventDeliveryException(this + ": Handshake timed out after " + connectTimeout + " ms", ex);
    } catch (InterruptedException ex) {
        throw new EventDeliveryException(this + ": Interrupted in handshake", ex);
    } catch (ExecutionException ex) {
        throw new EventDeliveryException(this + ": RPC request exception", ex);
    } catch (CancellationException ex) {
        throw new EventDeliveryException(this + ": RPC request cancelled", ex);
    } finally {
        if (!handshake.isDone()) {
            handshake.cancel(true);
        }
    }

    waitForStatusOK(callFuture, timeout, tu);
}

From source file:terrastore.store.impl.TCBucket.java

@Override
public Value update(final Key key, final Update update) throws StoreOperationException {
    long timeout = update.getTimeoutInMillis();
    Future<Value> task = null;
    // Use explicit locking to update and block concurrent operations on the same key,
    // and also publish on the same "transactional" boundary and keep ordering under concurrency.
    lockWrite(key);//from   ww w . ja v a  2s.c  o m
    try {
        final Value value = doGet(key);
        if (value != null) {
            final Function function = getFunction(updaters, update.getFunctionName());
            task = GlobalExecutor.getUpdateExecutor().submit(new Callable<Value>() {

                @Override
                public Value call() {
                    try {
                        return value.dispatch(key, update, function);
                    } catch (OperatorException ex) {
                        throw new RuntimeException(ex);
                    }
                }

            });
            Value result = task.get(timeout, TimeUnit.MILLISECONDS);
            doPut(key, result);
            if (eventBus.isEnabled()) {
                eventBus.publish(new ValueChangedEvent(name, key.toString(), value, result));
            }
            return result;
        } else {
            throw new StoreOperationException(
                    new ErrorMessage(ErrorMessage.NOT_FOUND_ERROR_CODE, "Key not found: " + key));
        }
    } catch (StoreOperationException ex) {
        throw ex;
    } catch (TimeoutException ex) {
        task.cancel(true);
        throw new StoreOperationException(new ErrorMessage(ErrorMessage.INTERNAL_SERVER_ERROR_CODE,
                "Update cancelled due to long execution time."));
    } catch (ExecutionException ex) {
        if (ex.getCause() instanceof RuntimeException
                && ex.getCause().getCause() instanceof OperatorException) {
            throw new StoreOperationException(((OperatorException) ex.getCause().getCause()).getErrorMessage());
        } else {
            throw new StoreOperationException(
                    new ErrorMessage(ErrorMessage.INTERNAL_SERVER_ERROR_CODE, ex.getMessage()));
        }
    } catch (Exception ex) {
        throw new StoreOperationException(
                new ErrorMessage(ErrorMessage.INTERNAL_SERVER_ERROR_CODE, ex.getMessage()));
    } finally {
        unlockWrite(key);
    }
}

From source file:com.seafile.seadroid2.provider.SeafileProvider.java

@Override
public AssetFileDescriptor openDocumentThumbnail(String documentId, Point sizeHint, CancellationSignal signal)
        throws FileNotFoundException {

    Log.d(DEBUG_TAG, "openDocumentThumbnail(): " + documentId);

    String repoId = DocumentIdParser.getRepoIdFromId(documentId);
    if (repoId.isEmpty()) {
        throw new FileNotFoundException();
    }/*from   ww  w .j a va  2s .c  o m*/

    String mimeType = Utils.getFileMimeType(documentId);
    if (!mimeType.startsWith("image/")) {
        throw new FileNotFoundException();
    }

    DataManager dm = createDataManager(documentId);

    String path = DocumentIdParser.getPathFromId(documentId);

    final DisplayImageOptions options = new DisplayImageOptions.Builder().extraForDownloader(dm.getAccount())
            .cacheInMemory(false) // SAF does its own caching
            .cacheOnDisk(true).considerExifParams(true).build();

    final ParcelFileDescriptor[] pair;
    try {
        pair = ParcelFileDescriptor.createReliablePipe();
    } catch (IOException e) {
        throw new FileNotFoundException();
    }

    final String url = dm.getThumbnailLink(repoId, path, sizeHint.x);
    if (url == null)
        throw new FileNotFoundException();

    // do thumbnail download in another thread to avoid possible network access in UI thread
    final Future future = ConcurrentAsyncTask.submit(new Runnable() {

        @Override
        public void run() {
            try {
                FileOutputStream fileStream = new FileOutputStream(pair[1].getFileDescriptor());

                // load the file. this might involve talking to the seafile server. this will hang until
                // it is done.
                Bitmap bmp = ImageLoader.getInstance().loadImageSync(url, options);

                if (bmp != null) {
                    bmp.compress(Bitmap.CompressFormat.PNG, 100, fileStream);
                }
            } finally {
                IOUtils.closeQuietly(pair[1]);
            }
        }
    });

    if (signal != null) {
        signal.setOnCancelListener(new CancellationSignal.OnCancelListener() {
            @Override
            public void onCancel() {
                Log.d(DEBUG_TAG, "openDocumentThumbnail() cancelling download");
                future.cancel(true);
                IOUtils.closeQuietly(pair[1]);
            }
        });
    }

    return new AssetFileDescriptor(pair[0], 0, AssetFileDescriptor.UNKNOWN_LENGTH);
}

From source file:org.apache.phoenix.query.BaseTest.java

private static void disableAndDropTable(final HBaseAdmin admin, final TableName tableName) throws Exception {
    Future<Void> future = null;
    boolean success = false;
    try {/*from  w w w  . jav a2  s. c om*/
        try {
            future = dropHTableService.submit(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    if (admin.isTableEnabled(tableName)) {
                        admin.disableTable(tableName);
                        admin.deleteTable(tableName);
                    }
                    return null;
                }
            });
            future.get(dropTableTimeout, TimeUnit.SECONDS);
            success = true;
        } catch (TimeoutException e) {
            throw new SQLExceptionInfo.Builder(SQLExceptionCode.OPERATION_TIMED_OUT)
                    .setMessage("Not able to disable and delete table " + tableName.getNameAsString() + " in "
                            + dropTableTimeout + " seconds.")
                    .build().buildException();
        } catch (Exception e) {
            throw e;
        }
    } finally {
        if (future != null && !success) {
            future.cancel(true);
        }
    }
}

From source file:de.blizzy.documentr.search.PageIndex.java

public SearchResult findPages(final String searchText, final int page, final Authentication authentication)
        throws ParseException, IOException, TimeoutException {

    Assert.hasLength(searchText);//from  ww w.j a  v a  2 s  .c  o m
    Assert.isTrue(page >= 1);
    Assert.notNull(authentication);

    IndexSearcher searcher = null;
    Future<SearchResult> findFuture = null;
    try {
        searcher = searcherManager.acquire();
        final IndexSearcher indexSearcher = searcher;

        Callable<SearchResult> findCallable = new Callable<SearchResult>() {
            @Override
            public SearchResult call() throws ParseException, IOException, TimeoutException {
                return findPages(searchText, page, authentication, indexSearcher);
            }
        };
        findFuture = taskExecutor.submit(findCallable);

        SearchTextSuggestion suggestion = getSearchTextSuggestion(searchText, authentication, indexSearcher);
        SearchResult result = findFuture.get(INTERACTIVE_TIMEOUT, TimeUnit.SECONDS);
        result.setSuggestion(suggestion);
        return result;
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    } catch (ExecutionException e) {
        Throwable cause = e.getCause();
        if (cause instanceof ParseException) {
            throw (ParseException) cause;
        } else if (cause instanceof IOException) {
            throw (IOException) cause;
        } else if (cause instanceof TimeoutException) {
            throw (TimeoutException) cause;
        } else {
            throw Util.toRuntimeException(cause);
        }
    } finally {
        if (findFuture != null) {
            findFuture.cancel(false);
        }
        if (searcher != null) {
            searcherManager.release(searcher);
        }
    }
}

From source file:org.apache.flume.api.NettyAvroRpcClient.java

private void appendBatch(List<Event> events, long timeout, TimeUnit tu) throws EventDeliveryException {

    assertReady();//from   w  w  w.j  a va  2  s .  co  m

    Iterator<Event> iter = events.iterator();
    final List<AvroFlumeEvent> avroEvents = new LinkedList<AvroFlumeEvent>();

    // send multiple batches... bail if there is a problem at any time
    while (iter.hasNext()) {
        avroEvents.clear();

        for (int i = 0; i < batchSize && iter.hasNext(); i++) {
            Event event = iter.next();
            AvroFlumeEvent avroEvent = new AvroFlumeEvent();
            avroEvent.setBody(ByteBuffer.wrap(event.getBody()));
            avroEvent.setHeaders(toCharSeqMap(event.getHeaders()));
            avroEvents.add(avroEvent);
        }

        final CallFuture<Status> callFuture = new CallFuture<Status>();

        Future<Void> handshake;
        try {
            // due to AVRO-1122, avroClient.appendBatch() may block
            handshake = callTimeoutPool.submit(new Callable<Void>() {

                @Override
                public Void call() throws Exception {
                    avroClient.appendBatch(avroEvents, callFuture);
                    return null;
                }
            });
        } catch (RejectedExecutionException ex) {
            throw new EventDeliveryException(this + ": Executor error", ex);
        }

        try {
            handshake.get(connectTimeout, TimeUnit.MILLISECONDS);
        } catch (TimeoutException ex) {
            throw new EventDeliveryException(this + ": Handshake timed out after " + connectTimeout + "ms", ex);
        } catch (InterruptedException ex) {
            throw new EventDeliveryException(this + ": Interrupted in handshake", ex);
        } catch (ExecutionException ex) {
            throw new EventDeliveryException(this + ": RPC request exception", ex);
        } catch (CancellationException ex) {
            throw new EventDeliveryException(this + ": RPC request cancelled", ex);
        } finally {
            if (!handshake.isDone()) {
                handshake.cancel(true);
            }
        }

        waitForStatusOK(callFuture, timeout, tu);
    }
}