List of usage examples for java.util.concurrent FutureTask FutureTask
public FutureTask(Callable<V> callable)
From source file:net.pms.io.ListProcessWrapperConsumer.java
@Override @Nullable/*from w w w. j a v a 2 s. c o m*/ public FutureTask<List<String>> consume(@Nullable final InputStream inputStream, @Nullable String threadName) { if (inputStream == null) { return null; } Callable<List<String>> callable = new Callable<List<String>>() { @Override public List<String> call() throws Exception { List<String> result = new ArrayList<>(); Charset outputCharset; if (Services.WINDOWS_CONSOLE != null) { outputCharset = Services.WINDOWS_CONSOLE; } else { outputCharset = StandardCharsets.UTF_8; } try (BufferedReader reader = new BufferedReader( new InputStreamReader(inputStream, outputCharset))) { String line; while ((line = reader.readLine()) != null) { result.add(line); } } if (LOGGER.isTraceEnabled()) { for (String line : result) { LOGGER.trace("Process output: {}", line); } } return result; } }; FutureTask<List<String>> result = new FutureTask<List<String>>(callable); Thread runner; if (isBlank(threadName)) { runner = new Thread(result); } else { runner = new Thread(result, threadName); } runner.start(); return result; }
From source file:org.apache.qpid.server.security.access.firewall.HostnameFirewallRule.java
/** * @param remote/*from w w w .ja v a 2 s. com*/ * the InetAddress to look up * @return the hostname, null if not found, takes longer than * {@value #DNS_LOOKUP} to find or otherwise fails */ private String getHostname(final InetAddress remote) throws AccessControlFirewallException { FutureTask<String> lookup = new FutureTask<String>(new Callable<String>() { public String call() { return remote.getCanonicalHostName(); } }); DNS_LOOKUP.execute(lookup); try { return lookup.get(DNS_TIMEOUT, TimeUnit.MILLISECONDS); } catch (Exception e) { _logger.warn("Unable to look up hostname from address " + remote, e); return null; } finally { lookup.cancel(true); } }
From source file:org.sakaiproject.tool.impl.SessionComponentRegressionTest.java
/** * Ensures {@link Session} has entity semantics, i.e. the same * object is returned to each request for that object. "Always" * here is limited to non-expired sessions. * // w w w .j a v a 2s.c o m * @throws TimeoutException * @throws ExecutionException * @throws InterruptedException */ public void testGetSessionAlwaysReturnsSessionCreatedByStartSession() throws InterruptedException, ExecutionException, TimeoutException { final Session startedSession = startSessionForUser(); assertSame(startedSession, sessionComponent.getSession(startedSession.getId())); assertSame(startedSession, sessionComponent.getSession(startedSession.getId())); // intentional duplicate // all threads should get the same Session obj for a given key FutureTask<Session> asynchGet = new FutureTask<Session>(new Callable<Session>() { public Session call() { return sessionComponent.getSession(startedSession.getId()); } }); new Thread(asynchGet).start(); assertSame(startedSession, asynchGet.get(1, TimeUnit.SECONDS)); }
From source file:net.pms.io.NullProcessWrapperConsumer.java
@Override @Nullable/*from w w w.j a v a 2 s.c om*/ public FutureTask<Void> consume(@Nullable final InputStream inputStream, @Nullable String threadName) { if (inputStream == null) { return null; } Callable<Void> callable = new Callable<Void>() { @Override public Void call() throws IOException { List<String> result = LOGGER.isTraceEnabled() ? new ArrayList<String>() : null; Charset outputCharset; if (Services.WINDOWS_CONSOLE != null) { outputCharset = Services.WINDOWS_CONSOLE; } else { outputCharset = StandardCharsets.UTF_8; } try (BufferedReader reader = new BufferedReader( new InputStreamReader(inputStream, outputCharset))) { String line; while ((line = reader.readLine()) != null) { if (result != null) { result.add(line); } } } if (result != null) { LOGGER.trace("Discarded {} lines of process output:", result.size()); for (String line : result) { LOGGER.trace(" Process output: {}", line); } } return null; } }; FutureTask<Void> result = new FutureTask<Void>(callable); Thread runner; if (isBlank(threadName)) { runner = new Thread(result); } else { runner = new Thread(result, threadName); } runner.start(); return result; }
From source file:com.ciphertool.sentencebuilder.etl.importers.FrequencyListImporterImpl.java
@Override public void importFrequencyList() { // Reset the counts in case this method is called again rowUpdateCount.set(0);/*from ww w . ja v a2s.c o m*/ rowInsertCount.set(0); long start = System.currentTimeMillis(); try { List<Word> wordsFromFile = frequencyFileParser.parseFile(); log.info("Starting frequency list import..."); List<FutureTask<Void>> futureTasks = new ArrayList<FutureTask<Void>>(); FutureTask<Void> futureTask = null; List<Word> threadedWordBatch = new ArrayList<Word>(); for (Word word : wordsFromFile) { threadedWordBatch.add(word); if (threadedWordBatch.size() >= this.concurrencyBatchSize) { List<Word> nextThreadedWordBatch = new ArrayList<Word>(); int originalSize = threadedWordBatch.size(); for (int i = 0; i < originalSize; i++) { /* * It's faster to remove from the end of the List * because no elements need to shift */ nextThreadedWordBatch.add(threadedWordBatch.remove(threadedWordBatch.size() - 1)); } futureTask = new FutureTask<Void>(new BatchWordImportTask(nextThreadedWordBatch)); futureTasks.add(futureTask); this.taskExecutor.execute(futureTask); } } /* * Start one last task if there are any leftover Words from file * that did not reach the batch size. */ if (threadedWordBatch.size() > 0) { /* * It's safe to use the threadedWordBatch now, instead of * copying into a temporaryList, because this is the last thread * to run. */ futureTask = new FutureTask<Void>(new BatchWordImportTask(threadedWordBatch)); futureTasks.add(futureTask); this.taskExecutor.execute(futureTask); } for (FutureTask<Void> future : futureTasks) { try { future.get(); } catch (InterruptedException ie) { log.error("Caught InterruptedException while waiting for BatchWordImportTask ", ie); } catch (ExecutionException ee) { log.error("Caught ExecutionException while waiting for BatchWordImportTask ", ee); } } } finally { log.info("Rows updated: " + this.rowUpdateCount); log.info("Rows inserted: " + this.rowInsertCount); log.info("Time elapsed: " + (System.currentTimeMillis() - start) + "ms"); } }
From source file:net.stuxcrystal.airblock.canary.CanaryServerBackend.java
@Override public <R> R callInMainThread(Callable<R> callable) throws Throwable { if (this.mTID == -1) throw new IllegalStateException("We do not know the main-thread id yet."); if (Thread.currentThread().getId() == this.mTID) { return callable.call(); }//from ww w. ja v a2 s. co m FutureTask<R> ft = new FutureTask<R>(callable); this.runLater(ft); return ft.get(); }
From source file:com.mobilesolutionworks.android.http.WorksHttpFutureTask.java
/** * Execute specified works http request in parallel. * * @param request works http request//from w w w. ja va2s. com * @param handler android handler * @param exec executor so it can be run in serial or other controlled manner */ public void execute(WorksHttpRequest request, Handler handler, Executor exec) { mWorker = new WorkerRunnable<WorksHttpRequest, Result>() { @Override public Result call() throws Exception { Thread.currentThread() .setUncaughtExceptionHandler(new UncaughtExceptionHandler(mHandler, mParams[0])); Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); WorksHttpResponse<Result> response = WorksHttpClient.executeOperation(mContext, mParams[0], WorksHttpFutureTask.this); return postResult(mHandler, response); } }; mFuture = new FutureTask<Result>(mWorker); mWorker.mHandler = handler; mWorker.mParams = new WorksHttpRequest[] { request }; exec.execute(mFuture); }
From source file:de.appsolve.padelcampus.utils.HtmlResourceUtil.java
public void updateCss(final ServletContext context) throws Exception { List<Customer> customers = customerDAO.findAll(); if (customers.isEmpty()) { applyCustomerCss(context, getDefaultCssAttributes(), ""); } else {/*from w w w .j a v a 2 s . c o m*/ lessCompiler = new LessCompiler(); lessCompiler.init(); int availableProcessors = Runtime.getRuntime().availableProcessors(); LOG.info(String.format("Compiling lesscss with %s cores", availableProcessors)); ExecutorService executor = Executors.newFixedThreadPool(availableProcessors); List<FutureTask<Void>> taskList = new ArrayList<>(); for (final Customer customer : customers) { FutureTask<Void> futureTask = new FutureTask<>(new Callable<Void>() { @Override public Void call() throws Exception { try { updateCss(context, customer); } catch (Exception ex) { LOG.error(ex, ex); } return null; } }); taskList.add(futureTask); executor.execute(futureTask); } for (FutureTask task : taskList) { task.get(); } executor.shutdown(); } }
From source file:org.springframework.batch.core.scope.AsyncJobScopeIntegrationTests.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 w w w. j a va 2 s .com public String call() throws Exception { JobExecution jobExecution = new JobExecution(id); ExecutionContext executionContext = jobExecution.getExecutionContext(); executionContext.put("foo", value); JobContext context = JobSynchronizationManager.register(jobExecution); logger.debug("Registered: " + context.getJobExecutionContext()); try { return simple.getName(); } finally { JobSynchronizationManager.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.jactr.core.module.AbstractModule.java
/** * create a future task and execute it on the exector * /*from www . j a v a 2 s . c o m*/ * @param <T> * @param caller * @param executor * @return */ static public <T> Future<T> delayedFuture(Callable<T> caller, Executor executor) { FutureTask<T> future = new FutureTask<T>(caller); if (executor != null) executor.execute(future); else future.run(); return future; }