List of usage examples for java.util.concurrent FutureTask get
public V get() throws InterruptedException, ExecutionException
From source file:org.t2framework.commons.util.LazyLoadingReference.java
public T get() throws IllegalStateException { while (true) { WeakReference<Future<T>> ref = reference.get(); boolean valid = true; if (ref == null) { FutureTask<T> f = new FutureTask<T>(new Callable<T>() { @Override//ww w .ja v a2 s. c om public T call() throws Exception { return factory.create(); } }); ref = new WeakReference<Future<T>>(f); if (valid = reference.compareAndSet(null, ref)) { f.run(); } } if (valid) { try { Future<T> f = ref.get(); if (f != null) { return f.get(); } else { reference.compareAndSet(ref, null); } } catch (CancellationException e) { reference.compareAndSet(ref, null); } catch (ExecutionException e) { throw new IllegalStateException(e.getCause()); } catch (Exception e) { throw new IllegalStateException(e); } } } }
From source file:org.commonreality.sensors.xml.XMLSensor.java
@Override public void stop() throws Exception { if (LOGGER.isDebugEnabled()) LOGGER.debug("Stopping"); _isStopping = true;/* w w w. ja v a 2s. c o m*/ synchronized (_pendingTimeFrames) { _pendingTimeFrames.clear(); } // clear out the trash FutureTask<Boolean> waitForMe = new FutureTask<Boolean>(new Runnable() { public void run() { } }, Boolean.TRUE); _service.execute(waitForMe); /* * interrupt the executor.. so that if it is currently waiting, say for the * clock.. */ _noOp.interrupt(); _processFrame.interrupt(); /* * and wait for it to finish */ waitForMe.get(); super.stop(); }
From source file:com.heliosdecompiler.helios.gui.controller.FileTreeController.java
public void updateTree(List<TreeNode> add, List<TreeNode> remove) { Set<TreeItem<TreeNode>> updated = new HashSet<>(); ArrayDeque<TreeNode> queue = new ArrayDeque<>(); queue.addAll(add);/* www. ja v a2 s . c o m*/ while (!queue.isEmpty()) { TreeNode thisNode = queue.pop(); TreeItem<TreeNode> parent; if (thisNode.getParent() == null) { parent = rootItem; } else { parent = itemMap.get(thisNode.getParent()); } updated.add(parent); TreeItem<TreeNode> thisItem = new TreeItem<>(thisNode); thisItem.addEventHandler(TreeItem.<TreeNode>branchExpandedEvent(), event -> { if (thisItem.getChildren().size() == 1) { thisItem.getChildren().get(0).setExpanded(true); } }); thisItem.setGraphic(new ImageView(new Image(getIconForTreeItem(thisNode)))); FutureTask<Void> call = new FutureTask<>(() -> { parent.getChildren().add(thisItem); return null; }); Platform.runLater(call); try { call.get(); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } itemMap.put(thisNode, thisItem); queue.addAll(thisNode.getChildren()); } for (TreeItem<TreeNode> parent : updated) { if (parent.getChildren().size() > 1) { FutureTask<Void> call = new FutureTask<>(() -> { parent.getChildren().sort((a, b) -> { int ac = a.getValue().getChildren().size(); int bc = b.getValue().getChildren().size(); if (ac == 0 && bc != 0) return 1; else if (ac != 0 && bc == 0) return -1; return a.getValue().getDisplayName().compareTo(b.getValue().getDisplayName()); }); return null; }); Platform.runLater(call); try { call.get(); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } } queue.addAll(remove); while (!queue.isEmpty()) { TreeNode thisNode = queue.pop(); TreeItem<TreeNode> thisItem = itemMap.remove(thisNode); thisItem.getParent().getChildren().remove(thisItem); queue.addAll(thisNode.getChildren()); } }
From source file:com.taobao.tair.comm.TairClientFactory.java
public TairClient get(final String targetUrl, final int connectionTimeout, final PacketStreamer pstreamer) throws TairClientException { String key = targetUrl;/*from w w w . j ava2s.c o m*/ FutureTask<TairClient> existTask = null; existTask = clients.get(key); if (existTask == null) { FutureTask<TairClient> task = new FutureTask<TairClient>(new Callable<TairClient>() { public TairClient call() throws Exception { return createClient(targetUrl, connectionTimeout, pstreamer); } }); existTask = clients.putIfAbsent(key, task); if (existTask == null) { existTask = task; task.run(); } } try { return existTask.get(); } catch (InterruptedException e) { throw new RuntimeException(e); } catch (CancellationException e) { // cancel exception may be lost connection fd, but we never called task.cancel(); clients.remove(key); throw e; } catch (ExecutionException e) { // create socket failed, so need not close clients.remove(key); throw new TairClientException("create socket exception, target address is " + targetUrl, e); } }
From source file:ubic.gemma.core.loader.util.fetcher.FtpFetcher.java
protected Collection<LocalFile> doTask(FutureTask<Boolean> future, long expectedSize, String seekFileName, String outputFileName) {/* w w w .j a v a 2 s . c o m*/ ExecutorService executor = Executors.newSingleThreadExecutor(); executor.execute(future); executor.shutdown(); try { File outputFile = new File(outputFileName); boolean ok = waitForDownload(future, expectedSize, outputFile); if (!ok) { // cancelled, probably. log.info("Download failed, was it cancelled?"); return null; } else if (future.get()) { if (log.isInfoEnabled()) log.info("Done: local file is " + outputFile); LocalFile file = fetchedFile(seekFileName, outputFile.getAbsolutePath()); Collection<LocalFile> result = new HashSet<>(); result.add(file); return result; } } catch (ExecutionException e) { throw new RuntimeException("Couldn't fetch " + seekFileName, e); } catch (InterruptedException e) { log.warn("Interrupted: Couldn't fetch " + seekFileName, e); return null; } catch (CancellationException e) { log.info("Cancelled"); return null; } throw new RuntimeException("Couldn't fetch file for " + seekFileName); }
From source file:edu.umass.cs.gnsserver.activecode.ActiveCodeHandler.java
/** * Runs the active code. Returns a {@link ValuesMap}. * * @param code64 base64 encoded active code, as stored in the db * @param guid the guid/* www .ja v a 2 s.co m*/ * @param field the field * @param action either 'read' or 'write' * @param valuesMap * @param activeCodeTTL the remaining active code TTL * @return a Valuesmap */ public ValuesMap runCode(String code64, String guid, String field, String action, ValuesMap valuesMap, int activeCodeTTL) { String code = new String(Base64.decodeBase64(code64)); String values = valuesMap.toString(); ValuesMap result = null; ActiveCodeParams acp = new ActiveCodeParams(guid, field, action, code, values, activeCodeTTL); FutureTask<ValuesMap> futureTask = new FutureTask<>(new ActiveCodeTask(acp, clientPool)); // If the guid is blacklisted, just return immediately if (isBlacklisted(guid)) { System.out.println("Guid " + guid + " is blacklisted from running code!"); return valuesMap; } // Only run if there are free workers and queue space // This prevents excessive CPU usage if (executorPool.getPoolSize() > 0 && executorPool.getQueue().remainingCapacity() > 0) { executorPool.execute(futureTask); try { result = futureTask.get(); } catch (ExecutionException e) { System.out.println("Added " + guid + " to blacklist!"); addToBlacklist(guid); } catch (InterruptedException e) { e.printStackTrace(); } } else { System.out.println("Rejecting task!"); } return result; }
From source file:com.liferay.portal.search.internal.SearchEngineInitializer.java
protected void doReIndex(int delay) { if (IndexWriterHelperUtil.isIndexReadOnly()) { return;/*w ww. jav a2s.com*/ } 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.jactr.eclipse.runtime.launching.session.SessionTracker.java
protected void launchQueued(boolean queryFirst) { if (queryFirst) { /*/* w w w . j a v a 2s. c o m*/ * prompt the user. should we defer? */ FutureTask<Integer> response = new FutureTask<Integer>(new Callable<Integer>() { public Integer call() { String[] buttons = new String[] { "Cancel All", "Run Queued" }; MessageDialog prompt = new MessageDialog(Display.getDefault().getActiveShell(), "Runs queued", null, "There are " + _queuedSessions.size() + " runs pending. Cancel them as well?", MessageDialog.QUESTION, buttons, 1); return prompt.open(); } }); Display.getDefault().syncExec(response); try { if (response.get() == 0) { _queuedSessions.clear(); return; } } catch (Exception e) { } } Object[] info = _queuedSessions.remove(0); ILaunchConfiguration configuration = (ILaunchConfiguration) info[0]; String mode = (String) info[1]; try { configuration.launch(mode, new NullProgressMonitor()); } catch (CoreException e) { CorePlugin.error("Could not launch deferred execution " + configuration.getName(), e); } }
From source file:com.datatorrent.stram.StramRecoveryTest.java
/** * Test serialization of the container manager with mock execution layer. * @throws Exception// w ww.ja v a 2 s . c o m */ private void testContainerManager(StorageAgent agent) throws Exception { dag.setAttribute(OperatorContext.STORAGE_AGENT, agent); StatsListeningOperator o1 = dag.addOperator("o1", StatsListeningOperator.class); FSRecoveryHandler recoveryHandler = new FSRecoveryHandler(dag.assertAppPath(), new Configuration(false)); StreamingContainerManager scm = StreamingContainerManager.getInstance(recoveryHandler, dag, false); File expFile = new File(recoveryHandler.getDir(), FSRecoveryHandler.FILE_SNAPSHOT); Assert.assertTrue("snapshot file " + expFile, expFile.exists()); PhysicalPlan plan = scm.getPhysicalPlan(); assertEquals("number required containers", 1, plan.getContainers().size()); PTOperator o1p1 = plan.getOperators(dag.getMeta(o1)).get(0); @SuppressWarnings("UnusedAssignment") /* sneaky: the constructor does some changes to the container */ MockContainer mc = new MockContainer(scm, o1p1.getContainer()); PTContainer originalContainer = o1p1.getContainer(); Assert.assertNotNull(o1p1.getContainer().bufferServerAddress); assertEquals(PTContainer.State.ACTIVE, o1p1.getContainer().getState()); assertEquals("state " + o1p1, PTOperator.State.PENDING_DEPLOY, o1p1.getState()); // test restore initial snapshot + log dag = StramTestSupport.createDAG(testMeta); scm = StreamingContainerManager .getInstance(new FSRecoveryHandler(dag.assertAppPath(), new Configuration(false)), dag, false); dag = scm.getLogicalPlan(); plan = scm.getPhysicalPlan(); o1p1 = plan.getOperators(dag.getOperatorMeta("o1")).get(0); assertEquals("post restore state " + o1p1, PTOperator.State.PENDING_DEPLOY, o1p1.getState()); o1 = (StatsListeningOperator) o1p1.getOperatorMeta().getOperator(); assertEquals("containerId", originalContainer.getExternalId(), o1p1.getContainer().getExternalId()); assertEquals("stats listener", 1, o1p1.statsListeners.size()); assertEquals("number stats calls", 0, o1.processStatsCnt); // stats are not logged assertEquals("post restore 1", PTContainer.State.ALLOCATED, o1p1.getContainer().getState()); assertEquals("post restore 1", originalContainer.bufferServerAddress, o1p1.getContainer().bufferServerAddress); StreamingContainerAgent sca = scm.getContainerAgent(originalContainer.getExternalId()); Assert.assertNotNull("allocated container restored " + originalContainer, sca); assertEquals("memory usage allocated container", (int) OperatorContext.MEMORY_MB.defaultValue, sca.container.getAllocatedMemoryMB()); // YARN-1490 - simulate container terminated on AM recovery scm.scheduleContainerRestart(originalContainer.getExternalId()); assertEquals("memory usage of failed container", 0, sca.container.getAllocatedMemoryMB()); Checkpoint firstCheckpoint = new Checkpoint(3, 0, 0); mc = new MockContainer(scm, o1p1.getContainer()); checkpoint(scm, o1p1, firstCheckpoint); mc.stats(o1p1.getId()).deployState(OperatorHeartbeat.DeployState.ACTIVE).currentWindowId(3) .checkpointWindowId(3); mc.sendHeartbeat(); assertEquals("state " + o1p1, PTOperator.State.ACTIVE, o1p1.getState()); // logical plan modification triggers snapshot CreateOperatorRequest cor = new CreateOperatorRequest(); cor.setOperatorFQCN(GenericTestOperator.class.getName()); cor.setOperatorName("o2"); CreateStreamRequest csr = new CreateStreamRequest(); csr.setSourceOperatorName("o1"); csr.setSourceOperatorPortName("outport"); csr.setSinkOperatorName("o2"); csr.setSinkOperatorPortName("inport1"); FutureTask<?> lpmf = scm.logicalPlanModification(Lists.newArrayList(cor, csr)); while (!lpmf.isDone()) { scm.monitorHeartbeat(); } Assert.assertNull(lpmf.get()); // unmask exception, if any Assert.assertSame("dag references", dag, scm.getLogicalPlan()); assertEquals("number operators after plan modification", 2, dag.getAllOperators().size()); // set operator state triggers journal write o1p1.setState(PTOperator.State.INACTIVE); Checkpoint offlineCheckpoint = new Checkpoint(10, 0, 0); // write checkpoint while AM is out, // it needs to be picked up as part of restore checkpoint(scm, o1p1, offlineCheckpoint); // test restore dag = StramTestSupport.createDAG(testMeta); scm = StreamingContainerManager .getInstance(new FSRecoveryHandler(dag.assertAppPath(), new Configuration(false)), dag, false); Assert.assertNotSame("dag references", dag, scm.getLogicalPlan()); assertEquals("number operators after restore", 2, scm.getLogicalPlan().getAllOperators().size()); dag = scm.getLogicalPlan(); plan = scm.getPhysicalPlan(); o1p1 = plan.getOperators(dag.getOperatorMeta("o1")).get(0); assertEquals("post restore state " + o1p1, PTOperator.State.INACTIVE, o1p1.getState()); o1 = (StatsListeningOperator) o1p1.getOperatorMeta().getOperator(); assertEquals("stats listener", 1, o1p1.statsListeners.size()); assertEquals("number stats calls post restore", 1, o1.processStatsCnt); assertEquals("post restore 1", PTContainer.State.ACTIVE, o1p1.getContainer().getState()); assertEquals("post restore 1", originalContainer.bufferServerAddress, o1p1.getContainer().bufferServerAddress); // offline checkpoint detection assertEquals("checkpoints after recovery", Lists.newArrayList(firstCheckpoint, offlineCheckpoint), o1p1.checkpoints); }
From source file:ubic.gemma.loader.util.fetcher.FtpFetcher.java
/** * @param future//from w w w. j a v a 2 s .com * @param expectedSize * @param outputFileName * @param seekFileName * @return */ protected Collection<LocalFile> doTask(FutureTask<Boolean> future, long expectedSize, String seekFileName, String outputFileName) { ExecutorService executor = Executors.newSingleThreadExecutor(); executor.execute(future); executor.shutdown(); try { File outputFile = new File(outputFileName); boolean ok = waitForDownload(future, expectedSize, outputFile); if (!ok) { // cancelled, probably. log.info("Download failed, was it cancelled?"); return null; } else if (future.get().booleanValue()) { if (log.isInfoEnabled()) log.info("Done: local file is " + outputFile); LocalFile file = fetchedFile(seekFileName, outputFile.getAbsolutePath()); Collection<LocalFile> result = new HashSet<LocalFile>(); result.add(file); return result; } } catch (ExecutionException e) { throw new RuntimeException("Couldn't fetch " + seekFileName, e); } catch (InterruptedException e) { log.warn("Interrupted: Couldn't fetch " + seekFileName, e); return null; } catch (CancellationException e) { log.info("Cancelled"); return null; } throw new RuntimeException("Couldn't fetch file for " + seekFileName); }