java.util.concurrent.FutureTask Java Examples
The following examples show how to use
java.util.concurrent.FutureTask.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TaskExecutorAdapter.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Override public Future<?> submit(Runnable task) { try { if (this.concurrentExecutor instanceof ExecutorService) { return ((ExecutorService) this.concurrentExecutor).submit(task); } else { FutureTask<Object> future = new FutureTask<Object>(task, null); this.concurrentExecutor.execute(future); return future; } } catch (RejectedExecutionException ex) { throw new TaskRejectedException( "Executor [" + this.concurrentExecutor + "] did not accept task: " + task, ex); } }
Example #2
Source File: ScriptCallableTest.java From commons-jexl with Apache License 2.0 | 6 votes |
@Test public void testFuture() throws Exception { JexlScript e = JEXL.createScript("while(true);"); FutureTask<Object> future = new FutureTask<Object>(e.callable(null)); ExecutorService executor = Executors.newFixedThreadPool(1); executor.submit(future); Object t = 42; try { t = future.get(100, TimeUnit.MILLISECONDS); Assert.fail("should have timed out"); } catch (TimeoutException xtimeout) { // ok, ignore future.cancel(true); } finally { executor.shutdown(); } Assert.assertTrue(future.isCancelled()); Assert.assertEquals(42, t); }
Example #3
Source File: HydroMetadataHandler.java From SensorWebClient with GNU General Public License v2.0 | 6 votes |
private void executeFoiTasks(Map<String, FutureTask<OperationResult>> getFoiAccessTasks, SOSMetadata metadata) throws InterruptedException, ExecutionException, XmlException, IOException, OXFException { int counter; counter = getFoiAccessTasks.size(); LOGGER.debug("Sending {} GetFeatureOfInterest requests", counter); for (String procedureID : getFoiAccessTasks.keySet()) { LOGGER.debug("Sending #{} GetFeatureOfInterest request for procedure '{}'", counter--, procedureID); FutureTask<OperationResult> futureTask = getFoiAccessTasks.get(procedureID); AccessorThreadPool.execute(futureTask); try { OperationResult opRes = futureTask.get(metadata.getTimeout(), MILLISECONDS); GetFeatureOfInterestParser getFoiParser = new GetFeatureOfInterestParser(opRes, metadata); getFoiParser.createFeatures(); } catch (TimeoutException e) { LOGGER.error("Timeout occured.", e); } } }
Example #4
Source File: TestEchoServer.java From new-bull with MIT License | 6 votes |
private void _test(EchoServer server) throws Exception { int port = new Random().nextInt(60000) + 1000; server.start(port); int threadCount = 100; Future[] futures = new Future[threadCount]; for (int i = 0; i < threadCount; i++) { final String msg = "task-" + i; FutureTask<Boolean> task = new FutureTask<>(() -> { String result = EchoClient.sendAndReceive(port, msg); return result.equals(msg); }); futures[i] = task; new Thread(task).start(); } for (Future<Boolean> f : futures) { Assert.assertTrue(f.get()); } }
Example #5
Source File: FileWriter.java From PackageTemplates with Apache License 2.0 | 6 votes |
public static PsiDirectory writeDirectory(PsiDirectory dir, DirectoryWrapper dirWrapper, Project project) { if (dir == null) { //todo print error return null; } RunnableFuture<PsiDirectory> runnableFuture = new FutureTask<>(() -> ApplicationManager.getApplication().runWriteAction(new Computable<PsiDirectory>() { @Override public PsiDirectory compute() { return writeDirectoryAction(dir, dirWrapper, project); } })); ApplicationManager.getApplication().invokeLater(runnableFuture); try { return runnableFuture.get(); } catch (InterruptedException | ExecutionException e) { Logger.log("runnableFuture " + e.getMessage()); Logger.printStack(e); } return null; }
Example #6
Source File: Java.java From restcommander with Apache License 2.0 | 6 votes |
/** * Try to discover what is hidden under a FutureTask (hack) */ public static Object extractUnderlyingCallable(FutureTask<?> futureTask) { try { Field syncField = FutureTask.class.getDeclaredField("sync"); syncField.setAccessible(true); Object sync = syncField.get(futureTask); Field callableField = sync.getClass().getDeclaredField("callable"); callableField.setAccessible(true); Object callable = callableField.get(sync); if (callable.getClass().getSimpleName().equals("RunnableAdapter")) { Field taskField = callable.getClass().getDeclaredField("task"); taskField.setAccessible(true); return taskField.get(callable); } return callable; } catch (Exception e) { throw new RuntimeException(e); } }
Example #7
Source File: Journal.java From database with GNU General Public License v2.0 | 6 votes |
/** * Warmup the indicated namespaces. * * @param namespaces * A list of zero or more namespaces to be warmed up (optional). * When <code>null</code> or empty, all namespaces will be warmed * up. * * @return A future for the task that is warming up the indices associated * with those namespace(s). The future evaluates to a map from the * name of the index to the statistics collected for that index * during the warmup procedure. * * @see <a href="http://trac.bigdata.com/ticket/1050" > pre-heat the journal * on startup </a> * * @see WarmUpTask */ public Future<Map<String, BaseIndexStats>> warmUp( final List<String> namespaces) { /* * The indices will be scanned with one thread per index. This parameter * determines the #of such scans that will execute in parallel. Since the * thread will block on any IO, you need a modestly large number of * threads here to enqueue enough disk reads to drive enough IOPs for an * efficient disk scan. */ final int nparallel = 20; final FutureTask<Map<String, BaseIndexStats>> ft = new FutureTask<Map<String, BaseIndexStats>>( new WarmUpTask(this, namespaces, ITx.READ_COMMITTED/* timestamp */, nparallel, false/* visitLeaves */)); getExecutorService().submit(ft); return ft; }
Example #8
Source File: ReformatAndOptimizeImportsProcessor.java From idea-android-studio-plugin with GNU General Public License v2.0 | 6 votes |
@Override @NotNull public FutureTask<Boolean> preprocessFile(@NotNull PsiFile file, boolean processChangedTextOnly) throws IncorrectOperationException { final FutureTask<Boolean> reformatTask = myReformatCodeProcessor.preprocessFile(file, processChangedTextOnly); final FutureTask<Boolean> optimizeImportsTask = myOptimizeImportsProcessor.preprocessFile(file, false); return new FutureTask<Boolean>(new Callable<Boolean>() { @Override public Boolean call() throws Exception { reformatTask.run(); if (!reformatTask.get() || reformatTask.isCancelled()) { return false; } CodeStyleManagerImpl.setSequentialProcessingAllowed(false); try { optimizeImportsTask.run(); return optimizeImportsTask.get() && !optimizeImportsTask.isCancelled(); } finally { CodeStyleManagerImpl.setSequentialProcessingAllowed(true); } } }); }
Example #9
Source File: TestMiniCoronaRunJob.java From RDFS with Apache License 2.0 | 6 votes |
public void testMemoryLimit() throws Exception { LOG.info("Starting testMemoryLimit"); JobConf conf = new JobConf(); conf.setInt(CoronaConf.NODE_RESERVED_MEMORY_MB, Integer.MAX_VALUE); corona = new MiniCoronaCluster.Builder().conf(conf).numTaskTrackers(2).build(); final JobConf jobConf = corona.createJobConf(); long start = System.currentTimeMillis(); FutureTask<Boolean> task = submitSleepJobFutureTask(jobConf); checkTaskNotDone(task, 10); NodeManager nm = corona.getClusterManager().getNodeManager(); nm.getResourceLimit().setNodeReservedMemoryMB(0); Assert.assertTrue(task.get()); long end = System.currentTimeMillis(); LOG.info("Task Done. Verifying"); new ClusterManagerMetricsVerifier(corona.getClusterManager(), 1, 1, 1, 1, 1, 1, 0, 0).verifyAll(); LOG.info("Time spent for testMemoryLimit:" + (end - start)); }
Example #10
Source File: WebappAuthenticator.java From AndroidChromium with Apache License 2.0 | 6 votes |
/** * Generates the authentication encryption key in a background thread (if necessary). */ private static void triggerMacKeyGeneration() { synchronized (sLock) { if (sKey != null || sMacKeyGenerator != null) { return; } sMacKeyGenerator = new FutureTask<SecretKey>(new Callable<SecretKey>() { // SecureRandomInitializer addresses the bug in SecureRandom that "TrulyRandom" // warns about, so this lint warning can safely be suppressed. @SuppressLint("TrulyRandom") @Override public SecretKey call() throws Exception { KeyGenerator generator = KeyGenerator.getInstance(MAC_ALGORITHM_NAME); SecureRandom random = new SecureRandom(); SecureRandomInitializer.initialize(random); generator.init(MAC_KEY_BYTE_COUNT * 8, random); return generator.generateKey(); } }); AsyncTask.THREAD_POOL_EXECUTOR.execute(sMacKeyGenerator); } }
Example #11
Source File: Wait.java From hawkular-apm with Apache License 2.0 | 6 votes |
/** * Blocks until the given condition evaluates to true. The condition is evaluated every @code{frequency} * milliseconds, so, the given condition should be an idempotent operation. * If the condition is not met within the given timeout, an exception is thrown. * * @param condition the condition to wait for * @param timeout the timeout value * @param timeUnit the unit for the timeout * @param frequency the frequency of the condition's evaluation in milliseconds */ public static void until(Callable<Boolean> condition, long timeout, TimeUnit timeUnit, long frequency) { FutureTask<Void> futureTask = new FutureTask<Void>(() -> { while (!condition.call()) { Thread.sleep(frequency); } return null; }); ExecutorService executor = Executors.newFixedThreadPool(1); executor.submit(futureTask); try { futureTask.get(timeout, timeUnit); } catch (InterruptedException | ExecutionException | TimeoutException e) { futureTask.cancel(true); e.printStackTrace(); Assert.fail(e.getMessage()); } }
Example #12
Source File: DeploymentScannerAdd.java From wildfly-core with GNU Lesser General Public License v2.1 | 6 votes |
@Override public Future<ModelNode> deploy(final ModelNode operation, final ExecutorService executorService) { try { deploymentOperation.set(operation); final FutureTask<ModelNode> task = new FutureTask<ModelNode>(new Callable<ModelNode>() { @Override public ModelNode call() throws Exception { deploymentDoneLatch.await(); return deploymentResults.get(); } }); executorService.submit(task); return task; } finally { scanDoneLatch.countDown(); } }
Example #13
Source File: ScheduledRunnableTest.java From RxJava3-preview with Apache License 2.0 | 6 votes |
@Test public void runFuture() { for (int i = 0; i < 500; i++) { CompositeDisposable set = new CompositeDisposable(); final ScheduledRunnable run = new ScheduledRunnable(Functions.EMPTY_RUNNABLE, set); set.add(run); final FutureTask<Void> ft = new FutureTask<Void>(Functions.EMPTY_RUNNABLE, null); Runnable r1 = new Runnable() { @Override public void run() { run.call(); } }; Runnable r2 = new Runnable() { @Override public void run() { run.setFuture(ft); } }; TestCommonHelper.race(r1, r2); } }
Example #14
Source File: SwingWorker.java From Bytecoder with Apache License 2.0 | 6 votes |
/** * Constructs this {@code SwingWorker}. */ public SwingWorker() { Callable<T> callable = new Callable<T>() { public T call() throws Exception { setState(StateValue.STARTED); return doInBackground(); } }; future = new FutureTask<T>(callable) { @Override protected void done() { doneEDT(); setState(StateValue.DONE); } }; state = StateValue.PENDING; propertyChangeSupport = new SwingWorkerPropertyChangeSupport(this); doProcess = null; doNotifyProgressChange = null; }
Example #15
Source File: FusionCohort.java From hmftools with GNU General Public License v3.0 | 6 votes |
private boolean checkThreadCompletion(final List<FutureTask> taskList) { try { for (FutureTask futureTask : taskList) { futureTask.get(); } } catch (Exception e) { ISF_LOGGER.error("task execution error: {}", e.toString()); e.printStackTrace(); return false; } return true; }
Example #16
Source File: DelegatorEcaHandler.java From scipio-erp with Apache License 2.0 | 6 votes |
public void setDelegator(Delegator delegator) { this.delegator = delegator; this.delegatorName = delegator.getDelegatorName(); this.entityEcaReaderName = EntityEcaUtil.getEntityEcaReaderName(delegator.getDelegatorBaseName()); Callable<DispatchContext> creator = new Callable<DispatchContext>() { public DispatchContext call() { return EntityServiceFactory.getDispatchContext(DelegatorEcaHandler.this.delegator); } }; FutureTask<DispatchContext> futureTask = new FutureTask<DispatchContext>(creator); if (this.dctx.compareAndSet(null, futureTask)) { ExecutionPool.GLOBAL_BATCH.submit(futureTask); } //preload the cache EntityEcaUtil.getEntityEcaCache(this.entityEcaReaderName); }
Example #17
Source File: Display3D.java From TrakEM2 with GNU General Public License v3.0 | 6 votes |
public Future<Collection<Future<Content>>> addContent(final Collection<Content> col) { final FutureTask<Collection<Future<Content>>> fu = new FutureTask<Collection<Future<Content>>>(new Callable<Collection<Future<Content>>>() { @Override public Collection<Future<Content>> call() { Thread.currentThread().setPriority(Thread.NORM_PRIORITY); try { return universe.addContentLater(col); } catch (final Throwable e) { IJError.print(e); return null; } }}); launchers.submit(new Runnable() { @Override public void run() { executors.submit(fu); }}); return fu; }
Example #18
Source File: BlazeProblemsView.java From intellij with Apache License 2.0 | 5 votes |
public BlazeProblemsView(Project project) { this.project = project; this.toolWindowId = Blaze.getBuildSystem(project).getName() + " Problems"; uiFuture = new FutureTask<>( () -> { BlazeProblemsViewPanel panel = new BlazeProblemsViewPanel(project); Disposer.register(project, () -> Disposer.dispose(panel)); createToolWindow(project, ToolWindowManager.getInstance(project), panel); return panel; }); UIUtil.invokeLaterIfNeeded(uiFuture); }
Example #19
Source File: BeakerCellExecutor.java From beakerx with Apache License 2.0 | 5 votes |
@Override public TryResult executeTask(Callable<TryResult> tsk, ExecutionOptions executionOptions) { FutureTask<TryResult> ret; try { theLock.lock(); ret = executeTaskInNewThread(tsk, executionOptions.getGroupName()); } catch (Throwable t) { t.printStackTrace(); return TryResult.createError(t.getMessage()); } finally { theLock.unlock(); } return getResult(ret); }
Example #20
Source File: AbstractWizard.java From netbeans with Apache License 2.0 | 5 votes |
final Object evaluateCall(final Object fn, final Object p) throws InterruptedException, ExecutionException { FutureTask<?> t = new FutureTask<Object>(new Callable<Object>() { @Override public Object call() throws Exception { JSObject jsRegFn = (JSObject) fn; return jsRegFn.call("call", null, p); } }); ctx.execute(t); return t.get(); }
Example #21
Source File: WebappAuthenticator.java From android-chromium with BSD 2-Clause "Simplified" License | 5 votes |
/** * Generates the authentication encryption key in a background thread (if necessary). */ private static void triggerMacKeyGeneration() { synchronized (sLock) { if (sKey != null || sMacKeyGenerator != null) { return; } sMacKeyGenerator = new FutureTask<SecretKey>(new Callable<SecretKey>() { @Override public SecretKey call() throws Exception { KeyGenerator generator = KeyGenerator.getInstance(MAC_ALGORITHM_NAME); SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); // Versions of SecureRandom from Android <= 4.3 do not seed themselves as // securely as possible. This workaround should suffice until the fixed version // is deployed to all users. getRandomBytes, which reads from /dev/urandom, // which is as good as the platform can get. // // TODO(palmer): Consider getting rid of this once the updated platform has // shipped to everyone. Alternately, leave this in as a defense against other // bugs in SecureRandom. byte[] seed = getRandomBytes(MAC_KEY_BYTE_COUNT); if (seed == null) { return null; } random.setSeed(seed); generator.init(MAC_KEY_BYTE_COUNT * 8, random); return generator.generateKey(); } }); AsyncTask.THREAD_POOL_EXECUTOR.execute(sMacKeyGenerator); } }
Example #22
Source File: CacheTemplate.java From smart-cache with Apache License 2.0 | 5 votes |
/** * 创建本地缓存 */ private Ehcache getEhcache(final String name) { Future<Ehcache> future = this.ehcaches.get(name); if (future == null) { Callable<Ehcache> callable = new Callable<Ehcache>() { @Override public Ehcache call() throws Exception { Ehcache cache = cacheManager.getEhcache(name); if (cache == null) { cacheManager.addCache(name); cache = cacheManager.getEhcache(name); } return cache; } }; FutureTask<Ehcache> task = new FutureTask<>(callable); future = this.ehcaches.putIfAbsent(name, task); if (future == null) { future = task; task.run(); } } try { return future.get(); } catch (Exception e) { this.ehcaches.remove(name); throw new CacheException(e); } }
Example #23
Source File: AwsObservableExtTest.java From titus-control-plane with Apache License 2.0 | 5 votes |
Future<RES> someAsyncOperation(AsyncHandler<? super REQ, RES> handler) { futureTask = new FutureTask<RES>(() -> { handler.onSuccess(request, response); return response; }); return futureTask; }
Example #24
Source File: ModernAsyncTask.java From V.FlyoutTest with MIT License | 5 votes |
/** * Creates a new asynchronous task. This constructor must be invoked on the UI thread. */ public ModernAsyncTask() { mWorker = new WorkerRunnable<Params, Result>() { public Result call() throws Exception { mTaskInvoked.set(true); Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); return postResult(doInBackground(mParams)); } }; mFuture = new FutureTask<Result>(mWorker) { @Override protected void done() { try { final Result result = get(); postResultIfNotInvoked(result); } catch (InterruptedException e) { android.util.Log.w(LOG_TAG, e); } catch (ExecutionException e) { throw new RuntimeException("An error occured while executing doInBackground()", e.getCause()); } catch (CancellationException e) { postResultIfNotInvoked(null); } catch (Throwable t) { throw new RuntimeException("An error occured while executing " + "doInBackground()", t); } } }; }
Example #25
Source File: PhenomenonFilteredHydroMetadataHandler.java From SensorWebClient with GNU General Public License v2.0 | 5 votes |
private Collection<SosTimeseries> executeGDATasks(Map<String, FutureTask<OperationResult>> getDataAvailabilityTasks, SOSMetadata metadata, Collection<SosTimeseries> observingTimeseries) throws InterruptedException, ExecutionException, TimeoutException, XmlException, IOException { int counter = getDataAvailabilityTasks.size(); LOGGER.debug("Sending " + counter + " GetDataAvailability requests"); Collection<SosTimeseries> timeseries = new ArrayList<SosTimeseries>(); for (String phenomenon : getDataAvailabilityTasks.keySet()) { LOGGER.debug("Sending #{} GetDataAvailability request for phenomenon " + phenomenon, counter--); FutureTask<OperationResult> futureTask = getDataAvailabilityTasks.get(phenomenon); AccessorThreadPool.execute(futureTask); OperationResult result = null; try { result = futureTask.get(SERVER_TIMEOUT, MILLISECONDS); } catch (Exception e) { LOGGER.error("Get no result for GetDataAvailability with parameter constellation: " + phenomenon + "!"); } if (result == null) { LOGGER.error("Get no result for GetDataAvailability with parameter constellation: " + phenomenon + "!"); } else { XmlObject result_xb = XmlObject.Factory.parse(result.getIncomingResultAsStream()); timeseries.addAll(getAvailableTimeseries(result_xb, phenomenon, metadata, observingTimeseries)); } } return timeseries; }
Example #26
Source File: ServletWrapperDelegatorServlet.java From nomulus with Apache License 2.0 | 5 votes |
@Override public void service(final HttpServletRequest req, final HttpServletResponse rsp) throws ServletException, IOException { FutureTask<Void> task = new FutureTask<>(new Callable<Void>() { @Nullable @Override public Void call() throws ServletException, IOException { // Simulate the full filter chain with the servlet at the end. final Iterator<Class<? extends Filter>> filtersIter = filterClasses.iterator(); FilterChain filterChain = new FilterChain() { @Override public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { if (filtersIter.hasNext()) { instantiate(filtersIter.next()).doFilter(request, response, this); } else { instantiate(servletClass).service(request, response); } }}; filterChain.doFilter(req, rsp); return null; }}); requestQueue.add(task); try { Uninterruptibles.getUninterruptibly(task); } catch (ExecutionException e) { throwIfInstanceOf(e.getCause(), ServletException.class); throwIfInstanceOf(e.getCause(), IOException.class); throw new RuntimeException(e.getCause()); } }
Example #27
Source File: TasksCachedProcessor.java From netbeans with Apache License 2.0 | 5 votes |
/** * Here I implemented following logic: * if it is requested to fetch the data and the same request is in progress - * result that returned is taken from the original one. * once task is completed, it is removed from cache! * */ @Override public R compute(final P arg) throws InterruptedException { Future<R> f = cache.get(arg); if (f == null) { Callable<R> evaluation = new Callable<R>() { @Override public R call() throws InterruptedException { return computable.compute(arg); } }; FutureTask<R> ft = new FutureTask<>(evaluation); f = cache.putIfAbsent(arg, ft); if (f == null) { f = ft; ft.run(); } } try { return f.get(); } catch (InterruptedException ex) { cache.remove(arg, f); throw new CancellationException(ex.getMessage()); } catch (Throwable th) { cache.remove(arg, f); if (log.isLoggable(Level.FINE)) { log.log(Level.FINE, "TasksCachedProcessor: exception while task execution:", th); // NOI18N } throw new CancellationException(th.getMessage()); } finally { if (removeOnCompletion) { cache.remove(arg, f); } } }
Example #28
Source File: ServletWrapperDelegatorServlet.java From nomulus with Apache License 2.0 | 5 votes |
ServletWrapperDelegatorServlet( Class<? extends HttpServlet> servletClass, ImmutableList<Class<? extends Filter>> filterClasses, Queue<FutureTask<Void>> requestQueue) { this.servletClass = servletClass; this.filterClasses = filterClasses; this.requestQueue = checkNotNull(requestQueue, "requestQueue"); }
Example #29
Source File: LibrarySectionAsyncTask.java From Mizuu with Apache License 2.0 | 5 votes |
/** * Creates a new asynchronous task. This constructor must be invoked on the UI thread. */ public LibrarySectionAsyncTask() { mWorker = new WorkerRunnable<Params, Result>() { public Result call() throws Exception { mTaskInvoked.set(true); Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); //noinspection unchecked return postResult(doInBackground(mParams)); } }; mFuture = new FutureTask<Result>(mWorker) { @Override protected void done() { try { postResultIfNotInvoked(get()); } catch (InterruptedException e) { android.util.Log.w(LOG_TAG, e); } catch (ExecutionException e) { throw new RuntimeException("An error occured while executing doInBackground()", e.getCause()); } catch (CancellationException e) { postResultIfNotInvoked(null); } } }; }
Example #30
Source File: PublisherFutureTest.java From reactive-streams-commons with Apache License 2.0 | 5 votes |
@Test public void constructors() { ConstructorTestBuilder ctb = new ConstructorTestBuilder(PublisherFuture.class); ctb.addRef("future", new FutureTask<>(() -> 1)); ctb.addLong("timeout", Long.MIN_VALUE, Long.MAX_VALUE); ctb.addRef("unit", TimeUnit.SECONDS); }