Java 类java.util.concurrent.FutureTask 实例源码

项目:RxJava3-preview    文件:ScheduledRunnableTest.java   
@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);
    }
}
项目:DecompiledMinecraft    文件:Util.java   
public static <V> V func_181617_a(FutureTask<V> p_181617_0_, Logger p_181617_1_)
{
    try
    {
        p_181617_0_.run();
        return p_181617_0_.get();
    }
    catch (ExecutionException executionexception)
    {
        p_181617_1_.fatal((String)"Error executing task", (Throwable)executionexception);
    }
    catch (InterruptedException interruptedexception)
    {
        p_181617_1_.fatal((String)"Error executing task", (Throwable)interruptedexception);
    }

    return (V)null;
}
项目:openjdk-jdk10    文件:DependencyFinder.java   
private Set<Location> waitForTasksCompleted() {
    try {
        Set<Location> targets = new HashSet<>();
        FutureTask<Set<Location>> task;
        while ((task = tasks.poll()) != null) {
            // wait for completion
            if (!task.isDone())
                targets.addAll(task.get());
        }
        return targets;
    } catch (InterruptedException|ExecutionException e) {
        throw new Error(e);
    }
}
项目:asura    文件:OffsetLimitInterceptor.java   
private <T> Future<T> call(Callable callable, boolean async){
    if(async){
         return Pool.submit(callable);
    }else{
        FutureTask<T> future = new FutureTask(callable);
        future.run();
        return future;
    }
}
项目:xbrowser    文件:Button.java   
public StringProperty textProperty() throws InterruptedException, ExecutionException {
    if (Platform.isFxApplicationThread()) {
        return ((javafx.scene.control.Button) body).textProperty();
    }
    final FutureTask<StringProperty> task = new FutureTask<>(() -> ((javafx.scene.control.Button) body).textProperty());
    Platform.runLater(task);
    return task.get();
}
项目:hadoop    文件:DeletionService.java   
@Override
protected void afterExecute(Runnable task, Throwable exception) {
  if (task instanceof FutureTask<?>) {
    FutureTask<?> futureTask = (FutureTask<?>) task;
    if (!futureTask.isCancelled()) {
      try {
        futureTask.get();
      } catch (ExecutionException ee) {
        exception = ee.getCause();
      } catch (InterruptedException ie) {
        exception = ie;
      }
    }
  }
  if (exception != null) {
    LOG.error("Exception during execution of task in DeletionService",
      exception);
  }
}
项目:IO    文件:EWFOutput.java   
/**
 * Creates a new EWFOutput with the given parameters.
 * @param toImage The device this image is of.
 * @param chunkQueue The source of data chunks to build the {@link SectorsSection Sectors} segments with.
 * @param outputFile The file to write the output to. Should end in .E01.
 * @param md5Hash The source of the MD5 digest hash.
 * @param sha1Hash The source of the SHA1 digest hash.
 * @param options The options used for this image.
 * @throws IOException
 */
public EWFOutput(Device toImage, BlockingQueue<Future<DataChunk>> chunkQueue, File outputFile,
        FutureTask<byte[]> md5Hash, FutureTask<byte[]> sha1Hash, AdvancedOptions options) throws IOException {
    super("EWFWriter");
    this.fileNumber = 1;
    this.outputFile = outputFile;
    this.expectedSize = toImage.getSize();
    this.serialNumber = toImage.getSerialNumber();
    this.volumeManager = new VolumeSectionManager(toImage);
    if (!outputFile.exists()) {
        if (this.outputFile.getParentFile() != null) {
            this.outputFile.getParentFile().mkdirs();
        }
        this.outputFile.createNewFile();
    }
    this.md5HashSource = md5Hash;
    this.sha1HashSource = sha1Hash;
    currentOutputFile = new RandomAccessFile(this.outputFile.getAbsolutePath(), "rw");
    currentOutputFile.setLength(0);
    this.chunkQueue = chunkQueue;
    this.sectorSize = 512; // TODO: remove hardcoded
    this.options = options;
    this.startTime = LocalDateTime.now();
}
项目:NIOHttp    文件:FutureDemo.java   
public void run(Consumer<HttpResponse> consumer) throws IOException {
System.out.println("Expecting a response after GET from: " + this.url.toString() + "\n\n");
try (SocketChannel socketChannel = SocketChannel.open(this.address)) {
    socketChannel.configureBlocking(true);
    writeGetRequestTo(socketChannel);

    FutureTask<Void> futureTask = HttpResponseReader.fromChannel(socketChannel, consumer);

    ExecutorService executor = Executors.newFixedThreadPool(1);
    executor.submit(futureTask);
    executor.awaitTermination(this.timeoutSeconds, TimeUnit.SECONDS);
    executor.shutdown();
    System.out.println("\n\nExecutor shutdown after waiting: " + this.timeoutSeconds + "s.");
} catch (InterruptedException e) {
    System.out.println("Error occured during task execution: " + e.getMessage());
}
   }
项目:incubator-netbeans    文件:JUnitProjectOpenedHook.java   
@Override
public java.util.concurrent.Future<ProjectProblemsProvider.Result> resolve() {
    ProjectProblemsProvider.Result res;
    if (action != null) {
        action.actionPerformed(null);
        String text = (String) action.getValue(ACT_START_MESSAGE);
        if (text != null) {
            res = ProjectProblemsProvider.Result.create(ProjectProblemsProvider.Status.RESOLVED, text);
        } else {
            res = ProjectProblemsProvider.Result.create(ProjectProblemsProvider.Status.RESOLVED);
        }
    } else {
        res = ProjectProblemsProvider.Result.create(ProjectProblemsProvider.Status.UNRESOLVED, "No resolution for the problem");
    }
    RunnableFuture<ProjectProblemsProvider.Result> f = new FutureTask(new Runnable() {
        @Override
        public void run() {
        }
    }, res);
    f.run();
    return f;
}
项目:JavaCommon    文件:FutureTaskDemo.java   
public static void main(String[] args) throws InterruptedException, ExecutionException {
    Date begin = new Date();
    Calculate calculate = new Calculate();
    int c = 0;

    //异步计算
    int two = 0;
    CallableDemo cDemo = new CallableDemo();
    cDemo.setCalculate(calculate);
    FutureTask<Integer> fTask = new FutureTask<>(cDemo);
    new Thread(fTask, "有返回值的线程").start();
    int one = calculate.calOne();
    two = fTask.get();

    //求和
    c = one + two;
    Date end = new Date();
    System.out.println("计算结果:" + c);
    long aaa = end.getTime() - begin.getTime();
    System.out.println("计算耗时:" + aaa);
}
项目:lttng-scope    文件:TestModelArrowProvider2.java   
@Override
public TimeGraphArrowRender getArrowRender(TimeGraphTreeRender treeRender, TimeRange timeRange, FutureTask<?> task) {
    TimeGraphArrowSeries series = getArrowSeries();
    List<TimeGraphTreeElement> treeElems = treeRender.getAllTreeElements();

    /* Draw 2 arrows total */
    TimeGraphEvent startEvent = new TimeGraphEvent(ts(timeRange, 0.3), treeElems.get(6));
    TimeGraphEvent endEvent = new TimeGraphEvent(ts(timeRange, 0.8), treeElems.get(4));
    TimeGraphArrow arrow1 = new TimeGraphArrow(startEvent, endEvent, series);

    startEvent = new TimeGraphEvent(ts(timeRange, 0.5), treeElems.get(10));
    endEvent = new TimeGraphEvent(ts(timeRange, 0.6), treeElems.get(7));
    TimeGraphArrow arrow2 = new TimeGraphArrow(startEvent, endEvent, series);

    List<TimeGraphArrow> arrows = ImmutableList.of(arrow1, arrow2);
    return new TimeGraphArrowRender(timeRange, arrows);
}
项目:lttng-scope    文件:TestModelStateProvider.java   
@Override
public TimeGraphStateRender getStateRender(TimeGraphTreeElement treeElement,
        TimeRange timeRange, long resolution, FutureTask<?> task) {

    int entryIndex = Integer.valueOf(treeElement.getName().substring(TestModelProvider.ENTRY_NAME_PREFIX.length()));
    long stateLength = entryIndex * DURATION_FACTOR;

    List<TimeGraphStateInterval> intervals = LongStream.iterate(timeRange.getStartTime(), i -> i + stateLength)
            .limit((timeRange.getDuration() / stateLength) + 1)
            .mapToObj(startTime -> {
                long endTime = startTime + stateLength - 1;
                StateDefinition stateDef = getNextStateDef();
                return new BasicTimeGraphStateInterval(startTime, endTime, treeElement, stateDef, stateDef.getName(), Collections.emptyMap());
            })
            .collect(Collectors.toList());

    return new TimeGraphStateRender(timeRange, treeElement, intervals);
}
项目:openjdk-jdk10    文件:FutureTaskTest.java   
/**
 * timed get with most negative timeout works correctly (i.e. no
 * underflow bug)
 */
public void testGet_NegativeInfinityTimeout() throws Exception {
    final ExecutorService pool = Executors.newFixedThreadPool(10);
    final Runnable nop = new Runnable() { public void run() {}};
    final FutureTask<Void> task = new FutureTask<>(nop, null);
    final List<Future<?>> futures = new ArrayList<>();
    Runnable r = new Runnable() { public void run() {
        for (long timeout : new long[] { 0L, -1L, Long.MIN_VALUE }) {
            try {
                task.get(timeout, NANOSECONDS);
                shouldThrow();
            } catch (TimeoutException success) {
            } catch (Throwable fail) {threadUnexpectedException(fail);}}}};
    for (int i = 0; i < 10; i++)
        futures.add(pool.submit(r));
    try {
        joinPool(pool);
        for (Future<?> future : futures)
            checkCompletedNormally(future, null);
    } finally {
        task.run();         // last resort to help terminate
    }
}
项目:lttng-scope    文件:TimeGraphArrowLayer.java   
private void paintArrowsOfProvider(TimeGraphTreeRender treeRender, TimeRange timeRange,
        TimeGraphModelArrowProvider arrowProvider, @Nullable FutureTask<?> task) {
    ArrowConfig config = fArrowProvidersConfig.get(arrowProvider);
    if (config == null) {
        /* Should not happen... */
        return;
    }

    TimeGraphArrowRender arrowRender = arrowProvider.getArrowRender(treeRender, timeRange, task);
    Collection<Arrow> arrows = prepareArrows(treeRender, arrowRender, config.getStroke());

    Platform.runLater(() -> {
        config.getGroup().getChildren().clear();
        config.getGroup().getChildren().addAll(arrows);
    });
}
项目:lttng-scope    文件:StubModelArrowProvider2.java   
@Override
public TimeGraphArrowRender getArrowRender(TimeGraphTreeRender treeRender, TimeRange timeRange, @Nullable FutureTask<?> task) {
    TimeGraphArrowSeries series = getArrowSeries();
    List<TimeGraphTreeElement> treeElems = treeRender.getAllTreeElements();

    /* Draw 2 arrows total */
    TimeGraphEvent startEvent = new TimeGraphEvent(ts(timeRange, 0.3), treeElems.get(6));
    TimeGraphEvent endEvent = new TimeGraphEvent(ts(timeRange, 0.8), treeElems.get(4));
    TimeGraphArrow arrow1 = new TimeGraphArrow(startEvent, endEvent, series);

    startEvent = new TimeGraphEvent(ts(timeRange, 0.5), treeElems.get(10));
    endEvent = new TimeGraphEvent(ts(timeRange, 0.6), treeElems.get(7));
    TimeGraphArrow arrow2 = new TimeGraphArrow(startEvent, endEvent, series);

    List<TimeGraphArrow> arrows = ImmutableList.of(arrow1, arrow2);
    return new TimeGraphArrowRender(timeRange, arrows);
}
项目:CustomWorldGen    文件:Util.java   
@Nullable
public static <V> V runTask(FutureTask<V> task, Logger logger)
{
    try
    {
        task.run();
        return task.get();
    }
    catch (ExecutionException executionexception)
    {
        logger.fatal((String)"Error executing task", (Throwable)executionexception);
    }
    catch (InterruptedException interruptedexception)
    {
        logger.fatal((String)"Error executing task", (Throwable)interruptedexception);
    }

    return (V)null;
}
项目:lttng-scope    文件:StubDrawnEventProviders.java   
@Override
public @NotNull TimeGraphDrawnEventRender getEventRender(TimeGraphTreeRender treeRender, TimeRange timeRange, @Nullable FutureTask<?> task) {
    TimeGraphDrawnEventSeries series = getDrawnEventSeries();

    List<TimeGraphDrawnEvent> events = treeRender.getAllTreeElements().stream()
            .filter(treeElem -> treeElem != StubModelProvider.ROOT_ELEMENT)
            /* Keep only entries (2, 4, 6, 8) */
            .filter(treeElem -> getIndexOfTreeElement(treeElem) < 10)
            .filter(treeElem -> getIndexOfTreeElement(treeElem) % 2 == 0)

            /* Draw symbols at positions (.1, .3, .5, .7, .9) */
            .flatMap(treeElem -> DoubleStream.iterate(0.1, i -> i + 0.2).limit(5)
                    .mapToObj(i -> new TimeGraphEvent(ts(timeRange, i), treeElem)))
            .map(event -> new TimeGraphDrawnEvent(event, series, null))
            .collect(ImmutableList.toImmutableList());

    /* There should be 20 symbols total */
    return new TimeGraphDrawnEventRender(timeRange, events);
}
项目:dss-demonstrations    文件:SigningTask.java   
private DSSPrivateKeyEntry getSigner(List<DSSPrivateKeyEntry> keys) throws Exception {
    DSSPrivateKeyEntry selectedKey = null;
    if (Utils.isCollectionEmpty(keys)) {
        throwException("No certificate found", null);
    } else if (Utils.collectionSize(keys) == 1) {
        selectedKey = keys.get(0);
    } else {
        FutureTask<DSSPrivateKeyEntry> future = new FutureTask<DSSPrivateKeyEntry>(new SelectCertificateTask(keys));
        Platform.runLater(future);
        selectedKey = future.get();
        if (selectedKey == null) {
            throwException("No selected certificate", null);
        }
    }
    return selectedKey;
}
项目:googles-monorepo-demo    文件:GeneratedMonitorTest.java   
@Override
protected void runTest() throws Throwable {
  final Runnable runChosenTest = new Runnable() {
    @Override public void run() { runChosenTest(); }
  };
  final FutureTask<Void> task = new FutureTask<Void>(runChosenTest, null);
  startThread(new Runnable() {
      @Override public void run() { task.run(); }
    });
  awaitUninterruptibly(doingCallLatch);
  long hangDelayMillis = (expectedOutcome == Outcome.HANG)
      ? EXPECTED_HANG_DELAY_MILLIS
      : UNEXPECTED_HANG_DELAY_MILLIS;
  boolean hung = !awaitUninterruptibly(
      callCompletedLatch, hangDelayMillis, TimeUnit.MILLISECONDS);
  if (hung) {
    assertEquals(expectedOutcome, Outcome.HANG);
  } else {
    assertNull(task.get(UNEXPECTED_HANG_DELAY_MILLIS, TimeUnit.MILLISECONDS));
  }
}
项目:Spring-Security-Third-Edition    文件:AsyncDispatcherServlet.java   
@Override
protected void doDispatch(final HttpServletRequest request, final HttpServletResponse response) throws Exception {

    final AsyncContext ac = request.startAsync(request, response);

    ac.setTimeout(TIME_OUT);

    // FIXME: convert to Lambda
    FutureTask task = new FutureTask(new Runnable() {

        @Override
        public void run() {
            try {
                logger.debug("Dispatching request " + request);
                AsyncDispatcherServlet.super.doDispatch(request, response);
                logger.debug("doDispatch returned from processing request " + request);
                ac.complete();
            } catch (Exception ex) {
                logger.error("Error in async request", ex);
            }
        }
    }, null);

    ac.addListener(new AsyncDispatcherServletListener(task));
    exececutor.execute(task);
}
项目:SpaceRace    文件:PathCreator.java   
private List<FutureTask<DistanceFrom>> calculateDistanceFromStart(@NonNull final LatLng start, @NonNull List<LatLng> points) {

        final String toMatch = "legs=[{distance={text=";
        List<FutureTask<DistanceFrom>> res = new ArrayList<>();
        final ExecutorService threadManager = Executors.newCachedThreadPool();
        final String init = start.latitude + "," + start.longitude;

        for (final LatLng destination : points) {

            final String dest = destination.latitude + "," + destination.longitude;
            final Call<Object> path = new PathRetrieval().getDirections(init, dest);

            FutureTask<DistanceFrom> task;
            if (MODE != MODE_DEBUG) {
                task = createTaskWithDistanceApi(start, destination, path, toMatch);
            } else {
                task = createTaskWithoutDistanceApi(start, destination);
            }
            res.add(task);
            threadManager.execute(task);
        }
        threadManager.shutdown();
        return res;
    }
项目:EasyTransaction    文件:BestEffortMessageMethodExecutor.java   
@SuppressWarnings("unchecked")
@Override
public <P extends EasyTransRequest<R,E>,E extends EasyTransExecutor,R extends Serializable> Future<R> execute(final Integer sameBusinessCallSeq, final P params) {
    FutureTask<PublishResult> future = new FutureTask<PublishResult>(new Callable<PublishResult>() {
        @Override
        public PublishResult call() throws Exception {
            return new PublishResult();//do nothing
        }
    });
    future.run();


    final LogProcessContext logProcessContext = transSynchronizer.getLogProcessContext();

    //sent message after transaction commit
    logProcessContext.registerProcessEndEventListener(new GuardianProcessEndEventHandler() {
        @Override
        public boolean beforeProcessEnd(LogProcessContext logContext) {
            if(logProcessContext.getFinalMasterTransStatus()){
                BusinessIdentifer businessIdentifer = ReflectUtil.getBusinessIdentifer(params.getClass());
                String messageId = getMessageId("M" + logProcessContext.getAndIncTransUniqueId(), logContext.getTransactionId());
                publisher.publish(businessIdentifer.appId(), businessIdentifer.busCode(), sameBusinessCallSeq, messageId, params,logProcessContext);
                LOG.info("Best effort message sent." + messageId);
            }
            return true;
        }
    });

    return (Future<R>) future;
}
项目:xbrowser    文件:Chart.java   
public StringProperty titleProperty()throws InterruptedException, ExecutionException{
    if(Platform.isFxApplicationThread()){
        return body.titleProperty();
    }
    final FutureTask<StringProperty> task = new FutureTask<>(()-> body.titleProperty());
    Platform.runLater(task);
    return task.get();

}
项目:RxJava3-preview    文件:AbstractDirectTaskTest.java   
@Test
public void finishedCancel() {
    AbstractDirectTask task = new AbstractDirectTask(Functions.EMPTY_RUNNABLE) {
        private static final long serialVersionUID = 208585707945686116L;
    };
    final Boolean[] interrupted = { null };
    FutureTask<Void> ft = new FutureTask<Void>(Functions.EMPTY_RUNNABLE, null) {
        @Override
        public boolean cancel(boolean mayInterruptIfRunning) {
            interrupted[0] = mayInterruptIfRunning;
            return super.cancel(mayInterruptIfRunning);
        }
    };

    task.set(AbstractDirectTask.FINISHED);

    assertTrue(task.isDisposed());

    task.dispose();

    assertTrue(task.isDisposed());

    task.setFuture(ft);

    assertTrue(task.isDisposed());

    assertNull(interrupted[0]);

    assertTrue(task.isDisposed());

    assertNull(interrupted[0]);
}
项目:GitHub    文件:CompressTask.java   
public static boolean compress(final ImageCompressor imageCompressor, final ImageMedia image, final long maxSize) {
    if (imageCompressor == null || image == null || maxSize <= 0) {
        return false;
    }
    FutureTask<Boolean> task = BoxingExecutor.getInstance().runWorker(new Callable<Boolean>() {
        @Override
        public Boolean call() throws Exception {
            final String path = image.getPath();
            File compressSaveFile = imageCompressor.getCompressOutFile(path);
            File needCompressFile = new File(path);
            if (BoxingFileHelper.isFileValid(compressSaveFile)) {
                image.setCompressPath(compressSaveFile.getAbsolutePath());
                return true;
            }
            if (!BoxingFileHelper.isFileValid(needCompressFile)) {
                return false;
            } else if (image.getSize() < maxSize) {
                image.setCompressPath(path);
                return true;
            } else {
                try {
                    File result = imageCompressor.compress(needCompressFile);
                    boolean suc = BoxingFileHelper.isFileValid(result);
                    image.setCompressPath(suc ? result.getAbsolutePath() : null);
                    return suc;
                } catch (IOException | OutOfMemoryError | NullPointerException | IllegalArgumentException e) {
                    image.setCompressPath(null);
                    BoxingLog.d("image compress fail!");
                }
            }
            return false;
        }
    });
    try {
        return task != null && task.get();
    } catch (InterruptedException | ExecutionException ignore) {
        return false;
    }
}
项目:GitHub    文件:CameraPickerHelper.java   
/**
 * start system camera to take a picture
 *
 * @param activity      not null if fragment is null.
 * @param fragment      not null if activity is null.
 * @param subFolderPath a folder in external DCIM,must start with "/".
 */
public void startCamera(final Activity activity, final Fragment fragment, final String subFolderPath) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M || !takePhotoSecure(activity, fragment, subFolderPath)) {
        FutureTask<Boolean> task = BoxingExecutor.getInstance().runWorker(new Callable<Boolean>() {
            @Override
            public Boolean call() throws Exception {
                try {
                    // try...try...try
                    Camera camera = Camera.open();
                    camera.release();
                } catch (Exception e) {
                    BoxingLog.d("camera is not available.");
                    return false;
                }
                return true;
            }
        });
        try {
            if (task != null && task.get()) {
                startCameraIntent(activity, fragment, subFolderPath, MediaStore.ACTION_IMAGE_CAPTURE, REQ_CODE_CAMERA);
            } else {
                callbackError();
            }
        } catch (InterruptedException | ExecutionException ignore) {
            callbackError();
        }

    }
}
项目:GitHub    文件:BitmapHunterTest.java   
@Test public void cancelMultipleRequests() {
  Action action1 = mockAction(URI_KEY_1, URI_1, mockImageViewTarget());
  Action action2 = mockAction(URI_KEY_1, URI_1, mockImageViewTarget());
  BitmapHunter hunter = new TestableBitmapHunter(picasso, dispatcher, cache, stats, action1);
  hunter.future = new FutureTask<>(mock(Runnable.class), mock(Object.class));
  hunter.attach(action2);
  assertThat(hunter.isCancelled()).isFalse();
  assertThat(hunter.cancel()).isFalse();
  hunter.detach(action1);
  hunter.detach(action2);
  assertThat(hunter.cancel()).isTrue();
  assertThat(hunter.isCancelled()).isTrue();
}
项目:RxJava3-preview    文件:FutureDisposableTest.java   
@Test
public void normalDone() {
    FutureTask<Object> ft = new FutureTask<Object>(Functions.EMPTY_RUNNABLE, null);
    FutureDisposable d = new FutureDisposable(ft, false);
    assertFalse(d.isDisposed());

    assertFalse(d.isDisposed());

    ft.run();

    assertTrue(d.isDisposed());
}
项目:Java-EX    文件:RxNullableTest.java   
@Test
public void testFuture() throws Exception {
  FutureTask<Object> future = new FutureTask<>(() -> null);
  future.run();
  RxNullable.fromFuture(future)
      .onNullDrop()
      .observable()
      .test()
      .assertValueCount(0);
  RxNullable.fromFuture(future)
      .onNullDrop()
      .flowable()
      .test()
      .assertValueCount(0);
}
项目:openjdk-jdk10    文件:CallerSensitiveFinder.java   
private void waitForCompletion() throws InterruptedException, ExecutionException {
    for (FutureTask<Void> t : tasks) {
        t.get();
    }
    if (tasks.isEmpty()) {
        throw new RuntimeException("No classes found, or specified.");
    }
    System.out.println("Parsed " + tasks.size() + " classfiles");
}
项目:openjdk-jdk10    文件:Customized.java   
static <V> void checkDone(final FutureTask<V> task) {
    try {
        check(task.isDone());
        check(! task.isCancelled());
        check(task.get() != null);
    } catch (Throwable t) { unexpected(t); }
}
项目:CloudNet    文件:DatabaseImpl.java   
@Deprecated
@Override
public FutureTask<Document> getDocumentAsync(String name)
{
    return new FutureTask<>(new Callable<Document>() {
        @Override
        public Document call() throws Exception
        {
            return getDocument(name);
        }
    });
}
项目:kognitivo    文件:LockOnGetVariable.java   
public LockOnGetVariable(final Callable<T> callable) {
    initLatch = new CountDownLatch(1);
    FacebookSdk.getExecutor().execute(
            new FutureTask<>(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    try {
                        LockOnGetVariable.this.value = callable.call();
                    } finally {
                        initLatch.countDown();
                    }
                    return null;
                }
            }));
}
项目:simple-share-android    文件:AsyncTask.java   
/**
 * Creates a new asynchronous task. This constructor must be invoked on the UI thread.
 */
public AsyncTask() {
    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);
            }
        }
    };
}
项目:incubator-netbeans    文件:JFXProjectProblems.java   
@NbBundle.Messages({"LBL_ResolveFXJDK=Choose FX-enabled Java Platform - \"{0}\" Project"})
@Override
public Future<Result> resolve() {
    final ChooseOtherPlatformPanel choosePlatform = new ChooseOtherPlatformPanel(type);
    final DialogDescriptor dd = new DialogDescriptor(choosePlatform, Bundle.LBL_ResolveFXJDK(ProjectUtils.getInformation(project).getDisplayName()));
    if (DialogDisplayer.getDefault().notify(dd) == DialogDescriptor.OK_OPTION) {
        final Callable<ProjectProblemsProvider.Result> resultFnc =
                new Callable<Result>() {
            @Override
            public Result call() throws Exception {
                final JavaPlatform jp = choosePlatform.getSelectedPlatform();
                if(jp != null) {
                    try {
                        ProjectManager.mutex().writeAccess(new Mutex.ExceptionAction<Void>() {
                            @Override
                            public Void run() throws IOException {
                                platformSetter.setProjectPlatform(jp);
                                JFXProjectUtils.updateClassPathExtension(project);
                                return null;
                            }
                        });
                    } catch (MutexException e) {
                        throw (IOException) e.getCause();
                    }
                    LOGGER.info("Set " + PLATFORM_ACTIVE + " to platform " + jp);
                    return ProjectProblemsProvider.Result.create(ProjectProblemsProvider.Status.RESOLVED);
                }
                return ProjectProblemsProvider.Result.create(ProjectProblemsProvider.Status.UNRESOLVED);
            }
        };
        final RunnableFuture<Result> result = new FutureTask<Result>(resultFnc);
        RP.post(result);
        return result;
    }
    return new JFXProjectProblems.Done(
            Result.create(ProjectProblemsProvider.Status.UNRESOLVED));
}
项目:tasfe-framework    文件:ThreadLocalAsyncExecutor.java   
@Override
public Future<?> submit(Runnable task) {
    logger.info("Submit runnable: {}", task);

    FutureTask<Object> future = new FutureTask<>(task, null);
    Object response = threadLocalResponses.get();
    futureTasks.putIfAbsent(response, future);

    return future;
}
项目:xbrowser    文件:Hyperlink.java   
public StringProperty textProperty() throws InterruptedException,ExecutionException {
    if (Platform.isFxApplicationThread()) {
        return ((javafx.scene.control.Hyperlink)body).textProperty();
    }
    final FutureTask<StringProperty> task = new FutureTask<>(() -> ((javafx.scene.control.Hyperlink)body).textProperty());
    Platform.runLater(task);
    return task.get();
}
项目:RxJava3-preview    文件:ScheduledRunnableTest.java   
@Test
public void setFutureRunRace() {
    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<Object> ft = new FutureTask<Object>(Functions.EMPTY_RUNNABLE, 0);

        Runnable r1 = new Runnable() {
            @Override
            public void run() {
                run.setFuture(ft);
            }
        };

        Runnable r2 = new Runnable() {
            @Override
            public void run() {
                run.run();
            }
        };

        TestCommonHelper.race(r1, r2);

        assertEquals(0, set.size());
    }
}
项目:xbrowser    文件:Control.java   
public double getWidth() throws InterruptedException,ExecutionException{

        if(Platform.isFxApplicationThread()){
            return getWidthBase();
        }
        final FutureTask<Double> task = new FutureTask<>(this::getWidthBase);
        Platform.runLater(task);
        return task.get();

//        if(body.getWidth() > 0.000001) return body.getWidth();
//        else return body.getPrefWidth();
    }
项目:incubator-netbeans    文件:AbstractWizard.java   
final Object evaluateProp(final String prop) throws InterruptedException, ExecutionException {
    FutureTask<?> t = new FutureTask<Object>(new Callable<Object>() {
        @Override
        public Object call() throws Exception {
            return getPropertyValue(data, prop);
        }
    });
    ctx.execute(t);
    return t.get();
}