Example usage for java.util.concurrent Future isDone

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

Introduction

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

Prototype

boolean isDone();

Source Link

Document

Returns true if this task completed.

Usage

From source file:org.apache.samza.system.hdfs.HdfsSystemConsumer.java

/**
 * {@inheritDoc}//w w w  .  ja  v a  2s.com
 */
@Override
public Map<SystemStreamPartition, List<IncomingMessageEnvelope>> poll(
        Set<SystemStreamPartition> systemStreamPartitions, long timeout) throws InterruptedException {
    systemStreamPartitions.forEach(systemStreamPartition -> {
        Future status = readerRunnableStatus.get(systemStreamPartition);
        if (status.isDone()) {
            try {
                status.get();
            } catch (ExecutionException | InterruptedException e) {
                MultiFileHdfsReader reader = readers.get(systemStreamPartition);
                LOG.warn(String.format("Detect failure in ReaderRunnable for ssp: %s. Try to reconnect now.",
                        systemStreamPartition), e);
                reader.reconnect();
                readerRunnableStatus.put(systemStreamPartition,
                        executorService.submit(new ReaderRunnable(reader)));
            }
        }
    });
    return super.poll(systemStreamPartitions, timeout);
}

From source file:org.codice.pubsub.server.SubscriptionServer.java

public int checkProcessingStatus(String subscriptionId) {

    Future<QueryControlInfo> future = processMap.get(subscriptionId);

    if (future != null) {
        boolean done = future.isDone();
        if (done) {
            return PROCESS_STATUS_COMPLETE;
        } else {//ww w  .  j  a  v  a  2s.c  om
            return PROCESS_STATUS_RUNNING;
        }
    } else {
        return PROCESS_STATUS_NOT_EXIST;
    }
}

From source file:gateway.test.ServiceTests.java

/**
 * Initialize mock objects./*from  www .j  av a2  s .c  o  m*/
 */
@Before
public void setup() {
    MockitoAnnotations.initMocks(this);
    MockitoAnnotations.initMocks(gatewayUtil);

    // Mock a common error we can use to test
    mockError = new ErrorResponse("Error!", "Test");

    // Mock a Service to use
    mockService = new Service();
    mockService.setServiceId("123456");
    mockService.setUrl("service.com");
    mockService.setResourceMetadata(new ResourceMetadata());
    mockService.getResourceMetadata().setName("Test");

    // Mock a user
    user = new JMXPrincipal("Test User");

    // Mock the Kafka response that Producers will send. This will always
    // return a Future that completes immediately and simply returns true.
    when(producer.send(isA(ProducerRecord.class))).thenAnswer(new Answer<Future<Boolean>>() {
        @Override
        public Future<Boolean> answer(InvocationOnMock invocation) throws Throwable {
            Future<Boolean> future = mock(FutureTask.class);
            when(future.isDone()).thenReturn(true);
            when(future.get()).thenReturn(true);
            return future;
        }
    });

    when(gatewayUtil.getErrorResponse(anyString())).thenCallRealMethod();
}

From source file:com.ctrip.infosec.rule.executor.PreRulesExecutorService.java

/**
 * /*from  ww  w.j  a  v a  2 s. co m*/
 */
void executeParallel(final RiskFact fact, List<PreRule> matchedRules) {

    final StatelessPreRuleEngine statelessPreRuleEngine = SpringContextHolder
            .getBean(StatelessPreRuleEngine.class);
    final String _logPrefix = Contexts.getLogPrefix();
    final String _traceLoggerParentTransId = TraceLogger.getTransId();

    List runs1 = Lists.newArrayList();
    for (final PreRule rule : matchedRules) {

        // ???
        boolean matched = Configs.match(rule.getConditions(), rule.getConditionsLogical(), fact.eventBody);
        if (!matched) {
            continue;
        }

        final String packageName = rule.getRuleNo();
        runs1.add(new Callable<Boolean>() {

            @Override
            public Boolean call() throws Exception {
                RuleMonitorHelper.newTrans(fact, RuleMonitorType.PRE_RULE, packageName);
                TraceLogger.beginTrans(fact.eventId);
                TraceLogger.setParentTransId(_traceLoggerParentTransId);
                TraceLogger.setLogPrefix("[" + packageName + "]");
                Contexts.setPolicyOrRuleNo(packageName);
                long start = System.currentTimeMillis();
                try {
                    // add current execute ruleNo and logPrefix before execution
                    fact.ext.put(Constants.key_ruleNo, rule.getRuleNo());
                    fact.ext.put(Constants.key_isAsync, true);
                    if (rule.getRuleType() == RuleType.Script) {
                        statelessPreRuleEngine.execute(packageName, fact);
                    } else if (rule.getRuleType() == RuleType.Visual) {
                        PreActionEnums preAction = PreActionEnums.parse(rule.getPreAction());
                        if (preAction != null) {
                            Converter converter = converterLocator.getConverter(preAction);
                            converter.convert(preAction, rule.getPreActionFieldMapping(), fact,
                                    rule.getPreActionResultWrapper(), false);
                        }
                    }
                    // remove current execute ruleNo when finished execution.
                    fact.ext.remove(Constants.key_ruleNo);
                    fact.ext.remove(Constants.key_isAsync);
                } catch (Throwable ex) {
                    logger.warn(_logPrefix + "?. preRule: " + packageName
                            + ", exception: " + ex.getMessage());
                    TraceLogger.traceLog("EXCEPTION: " + ex.toString());
                } finally {
                    long handlingTime = System.currentTimeMillis() - start;
                    if (handlingTime > 100) {
                        logger.info(_logPrefix + "preRule: " + packageName + ", usage: " + handlingTime + "ms");
                    }
                    TraceLogger.traceLog("[" + packageName + "] usage: " + handlingTime + "ms");
                    TraceLogger.commitTrans();
                    RuleMonitorHelper.commitTrans2Trunk(fact);
                    Contexts.clearLogPrefix();
                }
                return true;
            }
        });

    }

    // run
    try {
        if (!runs1.isEmpty()) {
            List<Future<Boolean>> results = ParallelExecutorHolder.excutor.invokeAll(runs1, timeout,
                    TimeUnit.MILLISECONDS);
            for (Future f : results) {
                try {
                    if (!f.isDone()) {
                        f.cancel(true);
                    }
                } catch (Exception e) {
                    // ignored
                }
            }
        }
    } catch (Exception ex) {
        // ignored
    }
}

From source file:com.ok2c.lightmtp.impl.protocol.PipeliningReceiveEnvelopCodec.java

@Override
public void produceData(final IOSession iosession, final ServerState sessionState)
        throws IOException, SMTPProtocolException {
    Args.notNull(iosession, "IO session");
    Args.notNull(sessionState, "Session state");

    SessionOutputBuffer buf = this.iobuffers.getOutbuf();

    synchronized (sessionState) {

        if (this.actionFuture != null) {
            SMTPReply reply = getReply(this.actionFuture);
            this.actionFuture = null;
            this.writer.write(reply, buf);
        }//from w  w  w.  ja v a 2  s.c o m

        if (this.actionFuture == null) {
            while (!this.pendingActions.isEmpty()) {
                Action<ServerState> action = this.pendingActions.remove();
                Future<SMTPReply> future = action.execute(sessionState,
                        new OutputTrigger<SMTPReply>(sessionState, iosession));
                if (future.isDone()) {
                    SMTPReply reply = getReply(future);
                    this.writer.write(reply, buf);
                } else {
                    this.actionFuture = future;
                    break;
                }
            }
        }

        if (buf.hasData()) {
            buf.flush(iosession.channel());
        }
        if (!buf.hasData()) {
            if (sessionState.getDataType() != null) {
                this.completed = true;
            }
            if (sessionState.isTerminated()) {
                iosession.close();
            } else {
                iosession.clearEvent(SelectionKey.OP_WRITE);
            }
        }
    }
}

From source file:org.jvnet.hudson.plugins.thinbackup.restore.HudsonRestore.java

private void restorePlugins(File toRestore) throws IOException {
    File[] list = toRestore.listFiles((FilenameFilter) FileFilterUtils.nameFileFilter("installedPlugins.xml"));

    if (list.length != 1) {
        LOGGER.severe(//w  w  w.jav a  2 s  .  c o m
                "Cannot restore plugins because no or mulitble files with the name 'installedPlugins.xml' are in the backup.");
        return;
    }

    File backupedPlugins = list[0];

    PluginList pluginList = new PluginList(backupedPlugins);
    pluginList.load();
    Map<String, String> toRestorePlugins = pluginList.getPlugins();
    List<Future<UpdateCenterJob>> pluginRestoreJobs = new ArrayList<Future<UpdateCenterJob>>(
            toRestorePlugins.size());
    PluginManager pluginManager = Hudson.getInstance().getPluginManager();
    for (Entry<String, String> entry : toRestorePlugins.entrySet()) {
        if (pluginManager.getPlugin(entry.getKey()) == null) { // if any version of this plugin is installed do nothing
            Future<UpdateCenterJob> monitor = installPlugin(entry.getKey(), entry.getValue());
            if (monitor != null)
                pluginRestoreJobs.add(monitor);
        } else
            LOGGER.info("Plugin '" + entry.getKey() + "' already installed. Please check manually.");
    }

    boolean finished = false;
    while (!finished) {
        try {
            Thread.sleep(SLEEP_TIMEOUT);
        } catch (InterruptedException e) {
            // nothing to do
        }
        for (Future<UpdateCenterJob> future : pluginRestoreJobs) {
            finished = future.isDone();
            if (!finished)
                break;
        }
    }
}

From source file:com.auditbucket.test.functional.TestForceDeadlock.java

private void doFutureWorked(Future<Integer> future, int count) throws Exception {
    while (!future.isDone()) {
        Thread.yield();//from  w  w  w  .j a  v a2 s .  co m
    }
    assertEquals(count, future.get().intValue());

}

From source file:org.rhq.server.control.command.Console.java

private int startInWindowsForeground(File binDir, String script, String... scriptArgs) throws Exception {
    org.apache.commons.exec.CommandLine commandLine = getConsoleCommandLine(script, scriptArgs);

    Future<Integer> f = ExecutorAssist.executeAsync(binDir, commandLine, null);
    // The program won't launch if rhqctl exits first, wait a few seconds
    for (int i = 0; (i < 3) && !f.isDone(); ++i) {
        Thread.sleep(1000);//from  w w  w  .j  av  a 2s  . c o  m
    }

    return f.isDone() ? f.get() : 0;
}

From source file:org.acmsl.queryj.tools.handlers.JdbcConnectionClosingHandler.java

/**
 * Waits until all generation threads have finish.
 * @param tasks the tasks.//  w w w  .j  av  a  2s  . c  om
 * @param log the {@link Log} instance.
 */
protected void waitUntilGenerationThreadsFinish(
        @NotNull final List<Future<? extends QueryJTemplate<QueryJTemplateContext>>> tasks,
        @Nullable final Log log) {
    for (@Nullable
    final Future<? extends QueryJTemplate<QueryJTemplateContext>> t_Task : tasks) {
        if (t_Task != null) {
            while (!t_Task.isDone()) {
                try {
                    if (log != null) {
                        log.debug("Waiting for " + t_Task.get().getTemplateContext().getTemplateName()
                                + " to finish");
                    }
                } catch (@NotNull final InterruptedException interrupted) {
                    log.info(INTERRUPTED_WHILE_WAITING_FOR_THE_THREADS_TO_FINISH, interrupted);
                } catch (@NotNull final ExecutionException interrupted) {
                    log.info(interrupted.getMessage());

                    Throwable cause = interrupted.getCause();

                    while (cause != null) {
                        log.error(cause.getMessage(), cause);
                        cause = cause.getCause();
                    }
                }

                synchronized (LOCK) {
                    try {
                        LOCK.wait(1000);
                    } catch (@NotNull final InterruptedException interrupted) {
                        if (log != null) {
                            log.info(INTERRUPTED_WHILE_WAITING_FOR_THE_THREADS_TO_FINISH, interrupted);
                        }
                    }
                }
            }
        }
    }
}

From source file:org.apache.roller.weblogger.business.runnable.ThreadManagerImpl.java

public void executeInForeground(Runnable runnable) throws InterruptedException {
    Future task = serviceScheduler.submit(runnable);

    // since this task is really meant to be executed within this calling 
    // thread, here we can add a little code here to loop until it realizes 
    // the task is done
    while (!task.isDone()) {
        Thread.sleep(500);//from  w w  w  .  j a  v  a2 s.  c  o m
    }
}