Example usage for java.util.concurrent Future isCancelled

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

Introduction

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

Prototype

boolean isCancelled();

Source Link

Document

Returns true if this task was cancelled before it completed normally.

Usage

From source file:com.clustercontrol.notify.util.ExecCommand.java

/**
 * ?????//from  w w w .jav  a2 s  .c  om
 *
 * @param outputInfo 
 */
private synchronized void executeCommand(OutputBasicInfo outputInfo, String notifyId) {
    if (m_log.isDebugEnabled()) {
        m_log.debug("executeCommand() " + outputInfo);
    }

    NotifyCommandInfo commandInfo;
    try {
        commandInfo = QueryUtil.getNotifyCommandInfoPK(notifyId);

        // commandInfo.getCommand()??command????????
        // commandInfo.getCommand()??????
        // TextReplacer????
        // command?????
        String command = getCommandString(outputInfo, commandInfo, outputInfo.getPriority());

        /**
         * 
         */
        // ???
        String sysUserName = System.getProperty("user.name");
        String effectiveUser = getEffectiveUser(commandInfo, outputInfo.getPriority());
        boolean setEnvFlag;
        if (commandInfo.getSetEnvironment().booleanValue()) {
            setEnvFlag = true;
        } else {
            setEnvFlag = false;
        }
        long commadTimeout = commandInfo.getTimeout();

        // Hinemos Manager??root????
        // ?????????
        if ((!sysUserName.equals("root")) && (!sysUserName.equals(effectiveUser))) {
            // 
            String detailMsg = "The execution user of the command and hinemos manager's user are different.";
            m_log.info(detailMsg);
            internalErrorNotify(PriorityConstant.TYPE_CRITICAL, notifyId,
                    MessageConstant.MESSAGE_SYS_007_NOTIFY, detailMsg);
            return;
        } else {
            m_log.debug("NotifyCommand Submit : " + outputInfo + " command=" + command);

            // ?
            Future<Long> ret = _callerExecutorService.submit(new CommandCallerTask(effectiveUser, command,
                    setEnvFlag, notifyId, outputInfo, commadTimeout));

            if (ret.isCancelled())
                m_log.debug("Cancelled NotifyCommand Submit : " + outputInfo + " command=" + command);
        }
    } catch (NotifyNotFound e) {
        String detailMsg = e.getMessage();
        m_log.info(
                "executeCommand() " + detailMsg + " : " + e.getClass().getSimpleName() + ", " + e.getMessage());
        internalErrorNotify(PriorityConstant.TYPE_CRITICAL, notifyId, MessageConstant.MESSAGE_SYS_007_NOTIFY,
                detailMsg);
    }
}

From source file:com.alibaba.otter.node.etl.load.loader.db.FileLoadAction.java

/**
 * ? fast-fail /*www.ja  v a 2  s . co m*/
 */
private void moveFiles(FileLoadContext context, List<FileData> fileDatas, File rootDir) {
    Exception exception = null;
    adjustPoolSize(context);
    ExecutorCompletionService<Exception> executorComplition = new ExecutorCompletionService<Exception>(
            executor);

    List<Future<Exception>> results = new ArrayList<Future<Exception>>();
    for (FileData fileData : fileDatas) {
        Future<Exception> future = executorComplition.submit(new FileLoadWorker(context, rootDir, fileData));
        results.add(future);

        // fast fail
        if (future.isDone()) { // ( CallerRunsPolicy)
            try {
                exception = future.get();
            } catch (Exception e) {
                exception = e;
            }
            if (exception != null) {
                for (Future<Exception> result : results) {
                    if (!result.isDone() && !result.isCancelled()) {
                        result.cancel(true);
                    }
                }
                throw exception instanceof LoadException ? (LoadException) exception
                        : new LoadException(exception);
            }
        }

    }

    int resultSize = results.size();
    int cursor = 0;
    while (cursor < resultSize) {
        try {
            Future<Exception> result = executorComplition.take();
            exception = result.get();
        } catch (Exception e) {
            exception = e;
            break;
        }
        cursor++;
    }

    if (cursor != resultSize) { // ??
        for (Future<Exception> future : results) {
            if (!future.isDone() && !future.isCancelled()) {
                future.cancel(true);
            }
        }

    }

    if (exception != null) {
        throw exception instanceof LoadException ? (LoadException) exception : new LoadException(exception);
    }
}

From source file:org.apache.solr.schema.ManagedIndexSchema.java

/**
 * Block up to a specified maximum time until we see agreement on the schema
 * version in ZooKeeper across all replicas for a collection.
 *///from  w  w w  .  j  av a2  s .  c o  m
public static void waitForSchemaZkVersionAgreement(String collection, String localCoreNodeName,
        int schemaZkVersion, ZkController zkController, int maxWaitSecs) {
    RTimer timer = new RTimer();

    // get a list of active replica cores to query for the schema zk version (skipping this core of course)
    List<GetZkSchemaVersionCallable> concurrentTasks = new ArrayList<>();
    for (String coreUrl : getActiveReplicaCoreUrls(zkController, collection, localCoreNodeName))
        concurrentTasks.add(new GetZkSchemaVersionCallable(coreUrl, schemaZkVersion));
    if (concurrentTasks.isEmpty())
        return; // nothing to wait for ...

    log.info("Waiting up to " + maxWaitSecs + " secs for " + concurrentTasks.size()
            + " replicas to apply schema update version " + schemaZkVersion + " for collection " + collection);

    // use an executor service to invoke schema zk version requests in parallel with a max wait time
    int poolSize = Math.min(concurrentTasks.size(), 10);
    ExecutorService parallelExecutor = ExecutorUtil.newMDCAwareFixedThreadPool(poolSize,
            new DefaultSolrThreadFactory("managedSchemaExecutor"));
    try {
        List<Future<Integer>> results = parallelExecutor.invokeAll(concurrentTasks, maxWaitSecs,
                TimeUnit.SECONDS);

        // determine whether all replicas have the update
        List<String> failedList = null; // lazily init'd
        for (int f = 0; f < results.size(); f++) {
            int vers = -1;
            Future<Integer> next = results.get(f);
            if (next.isDone() && !next.isCancelled()) {
                // looks to have finished, but need to check the version value too
                try {
                    vers = next.get();
                } catch (ExecutionException e) {
                    // shouldn't happen since we checked isCancelled
                }
            }

            if (vers == -1) {
                String coreUrl = concurrentTasks.get(f).coreUrl;
                log.warn("Core " + coreUrl + " version mismatch! Expected " + schemaZkVersion + " but got "
                        + vers);
                if (failedList == null)
                    failedList = new ArrayList<>();
                failedList.add(coreUrl);
            }
        }

        // if any tasks haven't completed within the specified timeout, it's an error
        if (failedList != null)
            throw new SolrException(ErrorCode.SERVER_ERROR,
                    failedList.size() + " out of " + (concurrentTasks.size() + 1)
                            + " replicas failed to update their schema to version " + schemaZkVersion
                            + " within " + maxWaitSecs + " seconds! Failed cores: " + failedList);

    } catch (InterruptedException ie) {
        log.warn("Core " + localCoreNodeName + " was interrupted waiting for schema version " + schemaZkVersion
                + " to propagate to " + concurrentTasks.size() + " replicas for collection " + collection);

        Thread.currentThread().interrupt();
    } finally {
        if (!parallelExecutor.isShutdown())
            parallelExecutor.shutdown();
    }

    log.info("Took {}ms for {} replicas to apply schema update version {} for collection {}", timer.getTime(),
            concurrentTasks.size(), schemaZkVersion, collection);
}

From source file:com.netflix.suro.sink.kafka.KafkaSinkV2.java

@Override
protected void write(List<Message> msgList) {
    QueuedSink.log.trace("KafkaSink write() with {} messages", msgList.size());
    // prepare "final" copies of the messages to be used in the anonymous class below
    final ArrayList<SuroKeyedMessage> msgCopies = new ArrayList<SuroKeyedMessage>(msgList.size());
    for (Message m : msgList) {
        SuroKeyedMessage sKeyedMsg = (SuroKeyedMessage) m;
        msgCopies.add(new SuroKeyedMessage(sKeyedMsg.getKey(), new Message(m.getRoutingKey(), m.getPayload())));
    }//from   w w  w.j  a v  a2  s.c om

    // The new KafkaProducer does not have interface for sending multiple messages,
    // so we loop and create lots of Runnables -- this seems inefficient, but the alternative
    // has its own problems.  If we create one "big Runnable" that loops over messages we'll
    // drain the queue4sink too quickly -- all the messages will be queued in the in-memory 
    // job queue storing the Runnables.
    for (final SuroKeyedMessage m : msgCopies) {
        senders.submit(new Runnable() {
            @Override
            public void run() {
                String topic = m.getRoutingKey();

                // calculate the kafka partition, with backward compatibility with old kafka producer
                int numPartitions = producer.partitionsFor(topic).size();
                int partition = Math.abs((int) (m.getKey() ^ (m.getKey() >>> 32))) % numPartitions;

                ProducerRecord r = new ProducerRecord(topic, partition, null, // don't store the key
                        m.getPayload());
                QueuedSink.log.trace("Will send message to Kafka");
                long startTimeMs = System.currentTimeMillis();
                // send
                Future<RecordMetadata> responseFtr = producer.send(r);
                QueuedSink.log.trace("Started aysnc producer");
                boolean failure = true;
                boolean retry = true;
                if (responseFtr.isCancelled()) {
                    QueuedSink.log.warn("Kafka producer request was cancelled");
                    // we assume that cancelled requests should not be retried.
                    retry = false;
                }
                try {
                    // wait for request to finish
                    RecordMetadata response = responseFtr.get();
                    if (response.topic() == null) {
                        QueuedSink.log.warn("Kafka producer got null topic in response");
                    }
                    sentCount.incrementAndGet();
                    sentByteCount.addAndGet(m.getPayload().length);
                    failure = false;
                    retry = false;
                } catch (InterruptedException e) {
                    // Assume that Interrupted means we're trying to shutdown so don't retry
                    QueuedSink.log.warn("Caught InterruptedException: " + e);
                    retry = false;
                } catch (UnknownTopicOrPartitionException e) {
                    QueuedSink.log.warn("Caught UnknownTopicOrPartitionException for topic: "
                            + m.getRoutingKey()
                            + " This may be simply because KafkaProducer does not yet have information about the brokers."
                            + " Request will be retried.");
                } catch (ExecutionException e) {
                    QueuedSink.log.warn("Caught ExecutionException: " + e);
                } catch (Exception e) {
                    QueuedSink.log.warn("Caught Exception: " + e);
                }
                long durationMs = System.currentTimeMillis() - startTimeMs;

                if (failure) {
                    QueuedSink.log.warn("Kafka producer send failed after {} milliseconds", durationMs);
                    requeuedCount.incrementAndGet();
                    if (retry) {
                        enqueue(m);
                    } else {
                        QueuedSink.log.info("Dropped message");
                        droppedCount.incrementAndGet();
                    }
                } else {
                    QueuedSink.log.trace("Kafka producer send succeeded after {} milliseconds", durationMs);
                }
            }
        });
    }
}

From source file:com.intel.cosbench.driver.service.MissionHandler.java

public void abort() {
    String id = missionContext.getId();
    Future<?> future = missionContext.getFuture();
    /* for strong consistency: a lock should be employed here */
    if (future != null) {
        if (future.isCancelled())
            return; // already aborted
        if (future.cancel(true))
            return; // abort request submitted
    }//w  w w .  jav a  2s  .c  om
    if (isStopped(missionContext.getState())) {
        LOGGER.warn("mission {} not aborted as it is already stopped", id);
        return; // do nothing -- it is already stopped
    }
    missionContext.setState(ABORTED); // abort it directly
    LOGGER.info("mission {} has been aborted successfully", id);
}

From source file:com.seyren.core.service.schedule.CheckScheduler.java

@Scheduled(fixedRateString = "${GRAPHITE_REFRESH:60000}")
public void performChecks() {
    int checksInScope = 0;
    int checksWereRun = 0;
    List<Check> checks = checksStore.getChecks(true, false).getValues();
    for (final Check check : checks) {
        // Skip any not in this instance's workload
        if (!isMyWork(check)) {
            continue;
        }/*  w  w w.ja  v  a  2 s  . c o m*/
        checksInScope++;
        // See if this check is currently running, if so, return and log the 
        // missed cycle
        if (!CheckConcurrencyGovernor.instance().isCheckRunning(check)) {
            checksWereRun++;
            // Notify the Check Governor that the check is now running
            CheckConcurrencyGovernor.instance().notifyCheckIsRunning(check);
            // Submit, so we can get the future, so we can control total time of execution
            final Future<?> checkExecutionFuture = executor.submit(checkRunnerFactory.create(check));
            // Schedule the cancellation (which will be a no-op if it has finished)
            executor.schedule(new Runnable() {
                public void run() {
                    checkExecutionFuture.cancel(true);
                    // Log that it was cancelled, if it was terminated
                    if (checkExecutionFuture.isCancelled()) {
                        LOGGER.warn("  *** Check #{} :: Check timed out", check.getId());

                        // Free this check as a fail-safe to not allow a resource issue to prevent checks from occurring
                        CheckConcurrencyGovernor.instance().notifyCheckIsComplete(check);
                    }
                }
            }, this.checkExecutionTimeoutSeconds, TimeUnit.SECONDS);
        } else {
            CheckConcurrencyGovernor.instance().logCheckSkipped(check);
            continue;
        }
    }
    // Log basic information about worker instance and its work
    LOGGER.info(String.format("Worker %d of %d is responsible for %d of %d checks, of which %d were run.",
            instanceIndex, totalWorkers, checksInScope, checks.size(), checksWereRun));
}

From source file:org.apache.http.impl.conn.FixedPoolingClientConnectionManager.java

ManagedClientConnection leaseConnection(final Future<HttpPoolEntry> future, final long timeout,
        final TimeUnit tunit) throws InterruptedException, ConnectionPoolTimeoutException {
    HttpPoolEntry entry;/*from w ww .j a v  a 2  s  . c o  m*/
    try {
        entry = future.get(timeout, tunit);
        if (entry == null || future.isCancelled()) {
            throw new InterruptedException();
        }
        if (entry.getConnection() == null) {
            throw new IllegalStateException("Pool entry with no connection");
        }
        if (this.log.isDebugEnabled()) {
            this.log.debug("Connection leased: " + format(entry) + formatStats(entry.getRoute()));
        }
        return new ManagedClientConnectionImpl(this, this.operator, entry);
    } catch (ExecutionException ex) {
        Throwable cause = ex.getCause();
        if (cause == null) {
            cause = ex;
        }
        this.log.error("Unexpected exception leasing connection from pool", cause);
        // Should never happen
        throw new InterruptedException();
    } catch (TimeoutException ex) {
        throw new ConnectionPoolTimeoutException("Timeout waiting for connection");
    }
}

From source file:org.apache.http2.impl.conn.PoolingClientConnectionManager.java

ManagedClientConnection leaseConnection(final Future<HttpPoolEntry> future, final long timeout,
        final TimeUnit tunit) throws InterruptedException, ConnectionPoolTimeoutException {
    HttpPoolEntry entry;/*from  www.j ava2s.c o  m*/
    try {
        entry = future.get(timeout, tunit);
        if (entry == null || future.isCancelled()) {
            throw new InterruptedException();
        }
        if (entry.getConnection() == null) {
            throw new IllegalStateException("Pool entry with no connection");
        }
        if (this.log.isDebugEnabled()) {
            this.log.debug("Connection leased: " + format(entry) + formatStats(entry.getRoute()));
        }
        return new ManagedClientConnectionImpl(this, this.operator, entry);
    } catch (ExecutionException ex) {
        Throwable cause = ex.getCause();
        if (cause == null) {
            cause = ex;
        }
        this.log.error("Unexpected exception leasing connection from pool", cause);
        // Should never happen
        throw new InterruptedException();
    } catch (TimeoutException ex) {
        throw new ConnectionPoolTimeoutException("Timeout waiting for connection from pool");
    }
}

From source file:org.apache.http.impl.conn.JMeterPoolingClientConnectionManager.java

ManagedClientConnection leaseConnection(final Future<HttpPoolEntry> future, final long timeout,
        final TimeUnit tunit) throws InterruptedException, ConnectionPoolTimeoutException {
    final HttpPoolEntry entry;
    try {// w ww. j a v  a 2 s  . c  o  m
        entry = future.get(timeout, tunit);
        if (entry == null || future.isCancelled()) {
            throw new InterruptedException();
        }
        Asserts.check(entry.getConnection() != null, "Pool entry with no connection");
        if (this.log.isDebugEnabled()) {
            this.log.debug("Connection leased: " + format(entry) + formatStats(entry.getRoute()));
        }
        return new ManagedClientConnectionImpl(this, this.operator, entry);
    } catch (final ExecutionException ex) {
        Throwable cause = ex.getCause();
        if (cause == null) {
            cause = ex;
        }
        this.log.error("Unexpected exception leasing connection from pool", cause);
        // Should never happen
        throw new InterruptedException();
    } catch (final TimeoutException ex) {
        throw new ConnectionPoolTimeoutException("Timeout waiting for connection from pool");
    }
}