下面列出了java.util.concurrent.FutureTask#get ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* deal with the system camera's shot.
*/
public boolean onActivityResult(final int requestCode, final int resultCode) {
if (requestCode != REQ_CODE_CAMERA) {
return false;
}
if (resultCode != Activity.RESULT_OK) {
callbackError();
return false;
}
FutureTask<Boolean> task = BoxingExecutor.getInstance().runWorker(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
return rotateImage(resultCode);
}
});
try {
if (task != null && task.get()) {
callbackFinish();
} else {
callbackError();
}
} catch (InterruptedException | ExecutionException ignore) {
callbackError();
}
return true;
}
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 phenomenonID : getFoiAccessTasks.keySet()) {
LOGGER.debug("Sending #{} GetFeatureOfInterest request for procedure '{}'", counter--, phenomenonID);
FutureTask<OperationResult> futureTask = getFoiAccessTasks.get(phenomenonID);
AccessorThreadPool.execute(futureTask);
try {
OperationResult opsRes = futureTask.get(SERVER_TIMEOUT, MILLISECONDS);
GetFeatureOfInterestParser getFoiParser = new GetFeatureOfInterestParser(opsRes, metadata);
getFoiParser.createFeatures();
}
catch (TimeoutException e) {
LOGGER.error("Timeout occured.", e);
}
}
}
private void registerIdleCallback() throws Exception {
FutureTask<Void> registerTask =
new FutureTask<Void>(
new Callable<Void>() {
@Override
public Void call() throws Exception {
resource.registerIdleTransitionCallback(mockCallback);
return null;
}
});
getInstrumentation().runOnMainSync(registerTask);
try {
registerTask.get();
} catch (ExecutionException ee) {
throw new RuntimeException(ee.getCause());
}
}
@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);
}
@Test
public void testTwoUpdates() throws StoreException, InterruptedException, ExecutionException {
final TestDefinition newTst1 = createDummyTestDefinition("3", "tst1");
final String description1 = "updated description tst1 from newTst1";
newTst1.setDescription(description1);
final TestDefinition newTst2 = createDummyTestDefinition("3", "tst1");
final String description2 = "updated description tst1 from newTst2";
newTst2.setDescription(description2);
final String lastRevision =
testee.getHistory(
"tst1", 0, 1
).get(0).getRevision();
final FutureTask<Boolean> future1 = getFutureTaskUpdateTestDefinition(lastRevision, "tst1", newTst1, "update description tst1");
final FutureTask<Boolean> future2 = getFutureTaskUpdateTestDefinition(lastRevision, "tst1", newTst2, "update description tst1");
startThreadsAndSleep(new Thread(future1), new Thread(future2));
final boolean thread1UpdateSuccess = future1.get();
final boolean thread2UpdateSuccess = future2.get();
assertTrue(thread1UpdateSuccess ^ thread2UpdateSuccess);
assertEquals(thread1UpdateSuccess ? description1 : description2, testee.getCurrentTestDefinition("tst1").getDescription());
assertFalse(testee.getRefreshTaskFuture().isCancelled());
}
/**
* Forces a refresh of the visualization based on current state of the
* underlying graph and waits for completion of the update.
*
* Use this variant only when necessary, e.g., need to style an element
* immediately after adding it to the underlying graph. Otherwise, use
* {@link #update() } instead for performance sake.
* <p>
* New vertices will be added close to adjacent ones or randomly for
* isolated vertices.
*/
public void updateAndWait() {
if (this.getScene() == null) {
throw new IllegalStateException("You must call this method after the instance was added to a scene.");
}
if (!this.initialized) {
throw new IllegalStateException("You must call init() method before any updates.");
}
final FutureTask update = new FutureTask(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
updateNodes();
return true;
}
});
//this will be called from a non-javafx thread, so this must be guaranteed to run of the graphics thread
Platform.runLater(update);
try {
//wait for completion
update.get();
} catch (InterruptedException | ExecutionException ex) {
Logger.getLogger(SmartGraphPanel.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Test
public void refreshShouldCancelRunningTaskWhenNewTaskIsSubmitted() throws Exception {
// Create a task that will block until we say to finish.
final FutureTask startedFirstTask = new FutureTask<>(() -> null);
final FutureTask<String> dependency = new FutureTask<>(() -> "first task");
final AtomicReference<Refreshable.Request> firstRequest = new AtomicReference<>();
final Refreshable.Callback<String> firstTask = (request) -> {
firstRequest.set(request);
startedFirstTask.run();
return dependency.get();
};
final Callable<String> secondTask = () -> "second task";
value.refresh(firstTask);
startedFirstTask.get(); // wait for first task to start running.
assertNull("should have blocked on the dependency", value.getNow());
checkLog("BUSY: null");
value.refresh(secondTask);
assertTrue("should have cancelled first task", firstRequest.get().isCancelled());
checkLog();
dependency.run(); // Make first task exit, allowing second to run.
expectUnpublish();
assertEquals("second task", value.getWhenReady());
checkLog("unpublished: first task",
"BUSY: second task",
"IDLE: second task");
}
@Test
public void testAbsolutePathOneAndTwo() throws Exception {
final String requestURI = "http://localhost:" + PORT + "/one/bookstore/request?delay";
Callable<String> callable = new Callable<String>() {
public String call() {
WebClient wc = WebClient.create(requestURI);
return wc.accept("text/plain").get(String.class);
}
};
FutureTask<String> task = new FutureTask<>(callable);
ExecutorService executor = Executors.newFixedThreadPool(1);
executor.execute(task);
Thread.sleep(1000);
Runnable runnable = new Runnable() {
public void run() {
try {
testAbsolutePathTwo();
} catch (Exception ex) {
throw new RuntimeException("Concurrent testAbsolutePathTwo failed");
}
}
};
new Thread(runnable).start();
Thread.sleep(2000);
String path = task.get();
assertEquals("Absolute RequestURI is wrong", requestURI, path);
}
public void check() throws Exception {
final FutureTask<Exception> futureTask = new FutureTask<>(this);
executor.submit(futureTask);
Exception x = futureTask.get();
if ( x != null) {
throw new RuntimeException("Check failed: "+x,x);
}
}
private boolean usesDaemonExecutor(HTTPServer httpServer) throws IOException, InterruptedException, ExecutionException {
try {
FutureTask<Boolean> task = new FutureTask<Boolean>(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
return Thread.currentThread().isDaemon();
}
});
httpServer.server.getExecutor().execute(task);
return task.get();
} finally {
httpServer.stop();
}
}
private boolean runOnHandlerThread(Callable<Boolean> callable) {
FutureTask<Boolean> futureTask = new FutureTask<>(callable);
mHandler.post(futureTask);
try {
return futureTask.get();
} catch (InterruptedException | ExecutionException e) {
Log.e(TAG, "Failed running callable.", e);
}
return false;
}
@Override
public boolean injectMotionEvent(final MotionEvent event) throws InjectEventSecurityException {
checkNotNull(event);
checkState(Looper.myLooper() == mainLooper, "Expecting to be on main thread!");
initialize();
FutureTask<Boolean> injectTask =
new SignalingTask<Boolean>(
new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
return eventInjector.injectMotionEvent(event);
}
},
IdleCondition.MOTION_INJECTION_HAS_COMPLETED,
generation);
Future<?> possiblyIgnoredError = keyEventExecutor.submit(injectTask);
loopUntil(IdleCondition.MOTION_INJECTION_HAS_COMPLETED, dynamicIdleProvider.get());
try {
checkState(injectTask.isDone(), "Motion event injection was signaled - but it wasnt done.");
return injectTask.get();
} catch (ExecutionException ee) {
if (ee.getCause() instanceof InjectEventSecurityException) {
throw (InjectEventSecurityException) ee.getCause();
} else {
throwIfUnchecked(ee.getCause() != null ? ee.getCause() : ee);
throw new RuntimeException(ee.getCause() != null ? ee.getCause() : ee);
}
} catch (InterruptedException neverHappens) {
// we only call get() after done() is signaled.
// we should never block.
throw new RuntimeException(neverHappens);
} finally {
loopMainThreadUntilIdle();
}
}
@Test
public void testQueryInfoCollectorReset() throws Exception {
prepareContexts();
enableCube("ci_left_join_cube");
ExecutorService executorService = Executors.newSingleThreadExecutor();
try {
String project = "default";
String expectedCube = "CUBE[name=ci_left_join_cube]";
String sqlWithCube = "select count(*) from test_kylin_fact";
FutureTask<String> queryTask1 = new FutureTask<String>(new QueryCallable(sqlWithCube, project, false));
executorService.submit(queryTask1);
String cubeName1 = queryTask1.get(2, TimeUnit.MINUTES);
Assert.assertTrue(queryTask1.isDone());
Assert.assertEquals(expectedCube, cubeName1);
String sqlNoCube = "select * from test_account";
FutureTask<String> queryTask2 = new FutureTask<String>(new QueryCallable(sqlNoCube, project, true));
executorService.submit(queryTask2);
String cubeName2 = queryTask2.get(2, TimeUnit.MINUTES);
Assert.assertTrue(queryTask2.isDone());
Assert.assertEquals(cubeName1, cubeName2);
FutureTask<String> queryTask3 = new FutureTask<String>(new QueryCallable(sqlNoCube, project, true));
executorService.submit(queryTask3);
String cubeName3 = queryTask3.get(2, TimeUnit.MINUTES);
Assert.assertTrue(queryTask3.isDone());
Assert.assertEquals("", cubeName3);
} finally {
executorService.shutdown();
cleanContexts();
}
}
public int countIssuesShown() throws InterruptedException, ExecutionException {
FutureTask<Integer> countIssues = new FutureTask<>(((ListPanel)
TestController.getUI().getPanelControl().getPanel(0))::getIssuesCount);
PlatformEx.runAndWait(countIssues);
return countIssues.get();
}
/**
* Unit test for correct visitation for a variety of offset/limit values.
*
* @throws ExecutionException
* @throws InterruptedException
*/
public void test_slice_offset1_limit3() throws InterruptedException,
ExecutionException {
final Var<?> x = Var.var("x");
final Var<?> y = Var.var("y");
final int bopId = 1;
final long offset = 1;
final long limit = 3;
final SliceOp query = new SliceOp(new BOp[]{},
NV.asMap(new NV[]{//
new NV(SliceOp.Annotations.BOP_ID, bopId),//
new NV(SliceOp.Annotations.OFFSET, offset),//
new NV(SliceOp.Annotations.LIMIT, limit),//
new NV(SliceOp.Annotations.EVALUATION_CONTEXT,
BOpEvaluationContext.CONTROLLER),//
new NV(PipelineOp.Annotations.SHARED_STATE,true),//
new NV(PipelineOp.Annotations.REORDER_SOLUTIONS,false),//
}));
assertEquals("offset", offset, query.getOffset());
assertEquals("limit", limit, query.getLimit());
// the expected solutions
final IBindingSet[] expected = new IBindingSet[] {//
new ListBindingSet(//
new IVariable[] { x, y },//
new IConstant[] { new Constant<String>("Mary"),
new Constant<String>("Paul"), }//
),
new ListBindingSet(//
new IVariable[] { x, y },//
new IConstant[] { new Constant<String>("Mary"),
new Constant<String>("Jane") }//
),
new ListBindingSet(//
new IVariable[] { x, y },//
new IConstant[] { new Constant<String>("Paul"),
new Constant<String>("Leon") }//
), };
final SliceStats stats = query.newStats();
final IAsynchronousIterator<IBindingSet[]> source = new ThickAsynchronousIterator<IBindingSet[]>(
new IBindingSet[][] { data.toArray(new IBindingSet[0]) });
final IBlockingBuffer<IBindingSet[]> sink = new BlockingBufferWithStats<IBindingSet[]>(query, stats);
final BOpContext<IBindingSet> context = new BOpContext<IBindingSet>(
new MockRunningQuery(null/* fed */, null/* indexManager */
, sink), -1/* partitionId */, stats, query/* op */,
false/* lastInvocation */, source, sink, null/* sink2 */);
// get task.
final FutureTask<Void> ft = query.eval(context);
ft.run();
AbstractQueryEngineTestCase.assertSameSolutions(expected, sink.iterator());
assertTrue(ft.isDone());
assertFalse(ft.isCancelled());
ft.get(); // verify nothing thrown.
assertEquals(limit, stats.naccepted.get());
assertEquals(offset+limit, stats.nseen.get());
assertEquals(1L, stats.chunksIn.get());
assertEquals(4L, stats.unitsIn.get());
assertEquals(3L, stats.unitsOut.get());
assertEquals(1L, stats.chunksOut.get());
}
@Override
final protected void doApply(final RemoteRepositoryManager rmgr,
final UUID uuid) throws Exception {
// Obtain task and wrap as FutureTask.
final FutureTask<Void> ft = new FutureTask<Void>(
getTask(rmgr, uuid));
begin(namespace, uuid, ft);
ft.run();// run in our thread.
try {
ft.get(); // check future.
} finally {
done(namespace, uuid);
}
}
static <T> T invokeAndWait(Callable<T> callable) throws Exception {
FutureTask<T> future = new FutureTask<T>(callable);
SwingUtilities.invokeLater(future);
return future.get();
}
private void waitForCompletion() throws InterruptedException, ExecutionException {
for (FutureTask<Void> t : tasks) {
t.get();
}
System.out.println("Parsed " + tasks.size() + " classfiles");
}
public static final void download(Library library, Release release) {
LibraryUpdater lib = new LibraryUpdater(library, release);
if (GraphicsEnvironment.isHeadless()) {
FutureTask<Object> task = new FutureTask<>(lib, null);
QUEUE.submit(task);
try {
task.get();
} catch (Exception exception) {
Log.error(exception);
}
} else {
// Close any open files that come from the library
Workspace workspace = Workspace.get();
Path prefix = library.getPath();
String title = library.getTitle();
for (Dockable dockable : workspace.getDock().getDockables()) {
if (dockable instanceof DataFileDockable) {
DataFileDockable dfd = (DataFileDockable) dockable;
Path path = dfd.getBackingFile();
if (path != null && path.toAbsolutePath().startsWith(prefix)) {
if (dfd.mayAttemptClose()) {
if (!dfd.attemptClose()) {
JOptionPane.showMessageDialog(null, String.format(I18n.Text("GCS %s update was canceled."), title), I18n.Text("Canceled!"), JOptionPane.INFORMATION_MESSAGE);
return;
}
}
}
}
}
// Put up a progress dialog
JDialog dialog = new JDialog(workspace, String.format(I18n.Text("Update %s"), title), true);
dialog.setResizable(false);
dialog.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
dialog.setUndecorated(true);
JComponent content = (JComponent) dialog.getContentPane();
content.setLayout(new BorderLayout());
content.setBorder(new CompoundBorder(new LineBorder(), new EmptyBorder(10)));
content.add(new JLabel(String.format(I18n.Text("Downloading and installing the %s…"), title)), BorderLayout.NORTH);
JProgressBar bar = new JProgressBar();
bar.setIndeterminate(true);
content.add(bar);
dialog.pack();
dialog.setLocationRelativeTo(workspace);
lib.mDialog = dialog;
QUEUE.submit(lib);
dialog.setVisible(true);
}
}
@Override
protected void doApply(final RemoteRepositoryManager rmgr,
final UUID uuid) throws Exception {
// Note: Do NOT assign the namespace until the task executes!!!
final String namespace = "n"
+ sharedTestState.namespaceCreateCounter.incrementAndGet();
// Wrap as FutureTask.
final FutureTask<Void> ft = new FutureTask<Void>(
new Callable<Void>() {
@Override
public Void call() throws Exception {
// Note: Wrap properties to avoid modification!
final Properties properties = new Properties(
sharedTestState.testMode.getProperties());
// create namespace.
rmgr.createRepository(namespace, properties);
// add entry IFF created.
if (sharedTestState.namespaces.putIfAbsent(namespace,
new ReentrantReadWriteLock()) != null) {
// Should not exist! Each namespace name is distinct!!!
throw new AssertionError("namespace=" + namespace);
}
// Track #of namespaces that exist in the service.
sharedTestState.namespaceExistCounter.incrementAndGet();
return null;
}
});
begin(namespace, uuid, ft);
ft.run(); // run in our thread.
try {
ft.get(); // check future.
} finally {
done(namespace, uuid);
}
}