Example usage for java.util.concurrent FutureTask FutureTask

List of usage examples for java.util.concurrent FutureTask FutureTask

Introduction

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

Prototype

public FutureTask(Callable<V> callable) 

Source Link

Document

Creates a FutureTask that will, upon running, execute the given Callable .

Usage

From source file:org.springframework.batch.core.scope.AsyncStepScopeIntegrationTests.java

@Test
public void testGetMultipleInMultipleThreads() throws Exception {

    List<FutureTask<String>> tasks = new ArrayList<FutureTask<String>>();

    for (int i = 0; i < 12; i++) {
        final String value = "foo" + i;
        final Long id = 123L + i;
        FutureTask<String> task = new FutureTask<String>(new Callable<String>() {
            @Override/*from   www.  j  a v  a  2  s  . c o  m*/
            public String call() throws Exception {
                StepExecution stepExecution = new StepExecution(value, new JobExecution(0L), id);
                ExecutionContext executionContext = stepExecution.getExecutionContext();
                executionContext.put("foo", value);
                StepContext context = StepSynchronizationManager.register(stepExecution);
                logger.debug("Registered: " + context.getStepExecutionContext());
                try {
                    return simple.getName();
                } finally {
                    StepSynchronizationManager.close();
                }
            }
        });
        tasks.add(task);
        taskExecutor.execute(task);
    }

    int i = 0;
    for (FutureTask<String> task : tasks) {
        assertEquals("foo" + i, task.get());
        i++;
    }

}

From source file:org.eclipse.virgo.ide.runtime.internal.core.command.AbstractJmxServerCommand.java

protected final Object execute(final JmxServerCommandTemplate template) throws TimeoutException {

    Callable<Object> deployOperation = new Callable<Object>() {

        public Object call() throws Exception {
            JMXConnector connector = null;
            try {
                connector = getJmxConnector();
                return template.invokeOperation(connector.getMBeanServerConnection());
            } finally {
                if (connector != null) {
                    try {
                        connector.close();
                    } catch (IOException e) {
                        SpringCore.log(e);
                    }//from w  ww  .  jav a2s.co  m
                }
            }
        }
    };

    FutureTask<Object> task = new FutureTask<Object>(deployOperation);
    ServerCorePlugin.EXECUTOR.submit(task);

    try {
        return task.get(30, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        // swallow exception here
    } catch (ExecutionException e) {
        // swallow exception here
    }

    return null;
}

From source file:com.appleframework.monitor.action.LogsAction.java

@RequestMapping(value = "/projects/{projectName}/logs/more", method = RequestMethod.GET)
public void console(final HttpServletResponse response, ModelMap map, @PathVariable String projectName,
        LogQuery logQuery) throws IOException, ParseException {
    Project project = projectService.findProject(projectName);
    map.put("project", project);
    final MongoConverter converter = project.fetchMongoTemplate().getConverter();
    final DBCursor cursor = logsService.findLogs(projectName, logQuery);
    final StringBuffer buf = new StringBuffer();

    FutureTask<String> task = new FutureTask<String>(new Callable<String>() {
        @Override//  w w w. ja  v  a2  s  .  c  o m
        public String call() throws Exception {
            long startTime = System.currentTimeMillis();
            //???20
            logger.debug("result:");
            while (cursor.hasNext()) {
                Log log = converter.read(Log.class, cursor.next());

                buf.insert(0, log.toString() + "\n");
                long current = System.currentTimeMillis();
                if ((current - startTime) / 1000 >= mongWaitSeconds)
                    break;
            }
            return buf.toString();
        }
    });
    executor.execute(task);
    try {
        task.get(mongWaitSeconds + 5, TimeUnit.SECONDS);
        cursor.close();
    } catch (Exception e) {
        logger.error("time out ", e);
        task.cancel(true);
    }

    response.setContentType("text/html;charset=UTF-8");
    response.getWriter().write(buf.toString());
    response.getWriter().flush();
}

From source file:com.skymobi.monitor.action.LogsAction.java

@RequestMapping(value = "/projects/{projectName}/logs/more", method = RequestMethod.GET)
public void console(final HttpServletResponse response, ModelMap map, @PathVariable String projectName,
        LogQuery logQuery) throws IOException, ParseException {
    Project project = projectService.findProject(projectName);
    map.put("project", project);
    final MongoConverter converter = project.fetchMongoTemplate().getConverter();
    final DBCursor cursor = logsService.findLogs(projectName, logQuery);
    final StringBuffer buf = new StringBuffer();
    @SuppressWarnings("unchecked")
    FutureTask<String> task = new FutureTask(new Callable<String>() {
        @Override//from   w w  w  .ja  v  a  2s. co  m
        public String call() throws Exception {
            long startTime = System.currentTimeMillis();
            //???20
            logger.debug("result:");
            while (cursor.hasNext()) {
                Log log = converter.read(Log.class, cursor.next());

                buf.insert(0, log.toString() + "\n");
                long current = System.currentTimeMillis();
                if ((current - startTime) / 1000 >= mongWaitSeconds)
                    break;
            }
            return buf.toString();
        }
    });
    executor.execute(task);
    try {
        task.get(mongWaitSeconds + 5, TimeUnit.SECONDS);
        cursor.close();
    } catch (Exception e) {
        logger.error("time out ", e);
        task.cancel(true);
    }

    response.setContentType("text/html;charset=UTF-8");
    response.getWriter().write(buf.toString());
    response.getWriter().flush();

}

From source file:com.liferay.portal.search.internal.SearchEngineInitializer.java

protected void doReIndex(int delay) {
    if (IndexWriterHelperUtil.isIndexReadOnly()) {
        return;/*from  w w w.j av a2  s  .  co  m*/
    }

    if (_log.isInfoEnabled()) {
        _log.info("Reindexing Lucene started");
    }

    if (delay < 0) {
        delay = 0;
    }

    try {
        if (delay > 0) {
            Thread.sleep(Time.SECOND * delay);
        }
    } catch (InterruptedException ie) {
    }

    ExecutorService executorService = _portalExecutorManager
            .getPortalExecutor(SearchEngineInitializer.class.getName());

    StopWatch stopWatch = new StopWatch();

    stopWatch.start();

    try {
        SearchEngineHelperUtil.removeCompany(_companyId);

        SearchEngineHelperUtil.initialize(_companyId);

        long backgroundTaskId = BackgroundTaskThreadLocal.getBackgroundTaskId();
        List<FutureTask<Void>> futureTasks = new ArrayList<>();
        Set<String> searchEngineIds = new HashSet<>();

        for (Indexer<?> indexer : IndexerRegistryUtil.getIndexers()) {
            String searchEngineId = indexer.getSearchEngineId();

            if (searchEngineIds.add(searchEngineId)) {
                IndexWriterHelperUtil.deleteEntityDocuments(searchEngineId, _companyId, indexer.getClassName(),
                        true);
            }

            FutureTask<Void> futureTask = new FutureTask<>(new Callable<Void>() {

                @Override
                public Void call() throws Exception {
                    BackgroundTaskThreadLocal.setBackgroundTaskId(backgroundTaskId);

                    reindex(indexer);

                    return null;
                }

            });

            executorService.submit(futureTask);

            futureTasks.add(futureTask);
        }

        for (FutureTask<Void> futureTask : futureTasks) {
            futureTask.get();
        }

        if (_log.isInfoEnabled()) {
            _log.info("Reindexing Lucene completed in " + (stopWatch.getTime() / Time.SECOND) + " seconds");
        }
    } catch (Exception e) {
        _log.error("Error encountered while reindexing", e);

        if (_log.isInfoEnabled()) {
            _log.info("Reindexing Lucene failed");
        }
    }

    _finished = true;
}

From source file:org.springframework.batch.core.step.tasklet.SystemCommandTasklet.java

/**
 * Execute system command and map its exit code to {@link ExitStatus} using
 * {@link SystemProcessExitCodeMapper}.//from   w w  w  .  j  a v a 2 s. c  o m
 */
@Override
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {

    FutureTask<Integer> systemCommandTask = new FutureTask<Integer>(new Callable<Integer>() {

        @Override
        public Integer call() throws Exception {
            Process process = Runtime.getRuntime().exec(command, environmentParams, workingDirectory);
            return process.waitFor();
        }

    });

    long t0 = System.currentTimeMillis();

    taskExecutor.execute(systemCommandTask);

    while (true) {
        Thread.sleep(checkInterval);//moved to the end of the logic

        if (stoppable) {
            JobExecution jobExecution = jobExplorer
                    .getJobExecution(chunkContext.getStepContext().getStepExecution().getJobExecutionId());

            if (jobExecution.isStopping()) {
                stopped = true;
            }
        }

        if (systemCommandTask.isDone()) {
            contribution.setExitStatus(systemProcessExitCodeMapper.getExitStatus(systemCommandTask.get()));
            return RepeatStatus.FINISHED;
        } else if (System.currentTimeMillis() - t0 > timeout) {
            systemCommandTask.cancel(interruptOnCancel);
            throw new SystemCommandException("Execution of system command did not finish within the timeout");
        } else if (execution.isTerminateOnly()) {
            systemCommandTask.cancel(interruptOnCancel);
            throw new JobInterruptedException(
                    "Job interrupted while executing system command '" + command + "'");
        } else if (stopped) {
            systemCommandTask.cancel(interruptOnCancel);
            contribution.setExitStatus(ExitStatus.STOPPED);
            return RepeatStatus.FINISHED;
        }
    }
}

From source file:com.alibaba.dragoon.common.protocol.DragoonSession.java

public Future<ResponseMessage> sendMessage(RequestMessage message) {
    int frameId = nextSequence();
    message.setFrameId(frameId);/*from   w  w w  . j a va  2  s.c o  m*/

    ResponseMessageTask task = new ResponseMessageTask();
    taskMap.put(frameId, task);

    FutureTask<ResponseMessage> future = new FutureTask<ResponseMessage>(task);
    futureMap.put(frameId, future);

    try {
        sentMessageCount.incrementAndGet();
        impl.sendMessageDirect(message);
    } catch (IOException e) {
        task.setError(e);
        future.run();
    }

    return future;
}

From source file:pt.webdetails.cpf.messaging.EventPublisher.java

private FutureTask<Result> getPublishTask(final PluginEvent event) {
    return new FutureTask<Result>(new Callable<Result>() {

        @Override/*from w  w  w . j a v a 2  s.  c om*/
        public Result call() throws Exception {
            JsonPluginCall call = new JsonPluginCall(InterPluginCall.CDV, "warnings");
            return new Result(call.call(event.toJSON()));
        }

    });
}

From source file:ubic.gemma.loader.util.fetcher.HttpFetcher.java

/**
 * @param outputFileName/*from w w  w .  jav  a  2s. c  o  m*/
 * @param seekFile
 * @return
 */
protected FutureTask<Boolean> defineTask(final String outputFileName, final String seekFile) {
    FutureTask<Boolean> future = new FutureTask<Boolean>(new Callable<Boolean>() {
        @Override
        @SuppressWarnings("synthetic-access")
        public Boolean call() throws FileNotFoundException, IOException {
            log.info("Fetching " + seekFile);
            URL urlPattern = new URL(seekFile);

            InputStream inputStream = new BufferedInputStream(urlPattern.openStream());
            OutputStream outputStream = new FileOutputStream(new File(outputFileName));

            final byte[] buffer = new byte[65536];
            int read = -1;

            while ((read = inputStream.read(buffer)) > -1) {
                outputStream.write(buffer, 0, read);
            }
            outputStream.close();
            return Boolean.TRUE;
        }
    });
    return future;
}

From source file:com.mrfeinberg.translation.AbstractTranslationService.java

public Runnable translate(final String phrase, final LanguagePair lp, final TranslationListener listener) {
    final Language b = lp.b();

    final HttpClient httpClient = new HttpClient();
    if (proxyPrefs.getUseProxy()) {
        httpClient.getHostConfiguration().setProxy(proxyPrefs.getProxyHost(), proxyPrefs.getProxyPort());
    }/* w  ww .jav  a2  s.co m*/

    final HttpMethod httpMethod = getHttpMethod(phrase, lp);
    final Callable<String> callable = new Callable<String>() {
        public String call() throws Exception {
            int result = httpClient.executeMethod(httpMethod);
            if (result != 200) {
                throw new Exception("Got " + result + " status for " + httpMethod.getURI());
            }
            final BufferedReader in = new BufferedReader(
                    new InputStreamReader(httpMethod.getResponseBodyAsStream(), "utf8"));
            try {
                final StringBuilder sb = new StringBuilder();
                String line;
                while ((line = in.readLine()) != null)
                    sb.append(line);
                return sb.toString();
            } finally {
                in.close();
                httpMethod.releaseConnection();
            }
        }
    };
    final FutureTask<String> tc = new FutureTask<String>(callable);
    return new Runnable() {
        public void run() {
            try {
                executor.execute(tc);
                final String result = tc.get(timeout, TimeUnit.MILLISECONDS);
                String found = findTranslatedText(result);
                if (found == null) {
                    listener.error("Cannot find translated text in result.");
                } else {
                    found = found.replaceAll("\\s+", " ");
                    listener.result(found, b);
                }
            } catch (final TimeoutException e) {
                listener.timedOut();
            } catch (final InterruptedException e) {
                listener.cancelled();
            } catch (final Exception e) {
                e.printStackTrace();
                listener.error(e.toString());
            }
        }
    };
}