Example usage for java.util.concurrent FutureTask run

List of usage examples for java.util.concurrent FutureTask run

Introduction

In this page you can find the example usage for java.util.concurrent FutureTask run.

Prototype

public void run() 

Source Link

Usage

From source file:net.dryuf.concurrent.benchmark.MixedListenerBenchmark.java

@Benchmark
@Warmup(iterations = WARMUP_ITERATIONS)//from w  ww  .  j  ava 2 s.co m
@Measurement(iterations = 2, batchSize = 1)
@Fork(warmups = 1, value = 1)
public void benchmarkJdk() throws Exception {
    for (long i = 0; i < COUNT; ++i) {
        FutureTask<Integer> future = new FutureTask<Integer>(() -> {
            return 0;
        });
        future.run();
        future.get();
    }
}

From source file:com.pepaproch.gtswsdl.client.RateLimitTest.java

private synchronized void addTask(AtomicInteger cc, ScheduledExecutorService schelduler, RateLimit rate,
        Instant[] end) {//  w ww  . j  av  a  2  s.co m

    Callable<Integer> callable = (Callable<Integer>) () -> {

        return cc.get();
    };
    ListenableFutureTask request = new ListenableFutureTask(callable);

    schelduler.schedule(() -> {
        FutureTask<?> schelduledTask = request;
        if (!request.isCancelled() && !request.isDone()) {
            schelduledTask.run();
        }

    }, rate.consumeSlot(), TimeUnit.MILLISECONDS);

    request.addCallback(new ListenableFutureCallback<Integer>() {

        @Override
        public void onSuccess(Integer result) {
            cc.incrementAndGet();
            end[0] = Instant.now();
            System.out.println("FINISHEDLISTENBALE: " + result + end[0].toString());
        }

        @Override
        public void onFailure(Throwable ex) {
            System.out.println("FAILURE");
        }
    });

}

From source file:com.github.gregwhitaker.asyncshowdown.HelloController.java

/**
 * Asynchronously waits a random random number of milliseconds, within the specified minimum and maximum, before
 * returning a 200 HTTP response with the body containing the string "Hello World!"
 *
 * @param minSleep minimum sleep time in milliseconds
 * @param maxSleep maximum sleep time in milliseconds
 * @return A 200 HTTP response with the body containing the string "Hello World!"
 *///from ww w. j  a va 2 s . co  m
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public DeferredResult<ResponseEntity<String>> hello(
        @RequestParam(name = "minSleepMs", defaultValue = "500") long minSleep,
        @RequestParam(name = "maxSleepMs", defaultValue = "500") long maxSleep) {
    final DeferredResult<ResponseEntity<String>> deferredResult = new DeferredResult<>();

    final FutureTask<String> helloTask = new FutureTask(new HelloGenerator(minSleep, maxSleep));
    Observable.<String>create(sub -> {
        String message = null;
        try {
            helloTask.run();
            message = helloTask.get();
        } catch (Exception e) {
            sub.onError(e);
        }
        sub.onNext(message);
        sub.onCompleted();
    }).last().subscribeOn(Schedulers.io()).subscribe(
            message -> deferredResult.setResult(ResponseEntity.ok(message)),
            error -> deferredResult.setResult(ResponseEntity.status(500).body(error.getMessage())));

    return deferredResult;
}

From source file:org.punksearch.util.RenewableMemoizer.java

public V compute(final A arg) throws InterruptedException {
    __log.debug("Compute: " + arg);
    while (true) {
        Future<V> f = cache.get(arg);
        if (f == null) {
            FutureTask<V> ft = makeFutureTask(arg);
            f = cache.putIfAbsent(arg, ft);
            if (f == null) {
                f = ft;/*from  ww  w.  jav  a2s .  c  o m*/
                ft.run();
            }
        } else {
            assert timestamps.get(arg) != null; // once put to timestamps value is never removed from it
            if (timestamps.get(arg) + timeout < System.currentTimeMillis()) {
                __log.debug("Item expired, removing from cache: " + arg);
                cache.remove(arg, f);
                continue;
            }
        }
        try {
            return f.get();
        } catch (CancellationException e) {
            cache.remove(arg, f);
        } catch (ExecutionException e) {
            throw LaunderThrowable.launderThrowable(e.getCause());
        }
    }
}

From source file:com.alibaba.dragoon.common.protocol.DragoonSession.java

public void close() {
    for (Map.Entry<Integer, ResponseMessageTask> entry : taskMap.entrySet()) {
        if (lastError != null) {
            entry.getValue().setError(lastError);
        }//from   ww  w .j a  v a  2 s  .com

        FutureTask<ResponseMessage> future = futureMap.get(entry.getKey());
        future.run();
    }

    new DragoonIoFilterChainImpl(config).sessionClosed(this);
}

From source file:gridool.construct.GridTaskAdapter.java

public final Serializable invokeTask() throws GridException {
    final FutureTask<Serializable> runningTask = new FutureTask<Serializable>(this);
    this.running = runningTask;
    runningTask.run();
    try {// w w  w. j  a  va2 s  . co m
        return runningTask.get();
    } catch (InterruptedException e) {
        LOG.warn("task canceled: " + getTaskId());
        throw TaskCancelException.getInstance();
    } catch (ExecutionException e) {
        throw new GridException(e);
    } finally {
        this.running = null;
    }
}

From source file:com.github.jknack.handlebars.cache.HighConcurrencyTemplateCache.java

/**
 * Compute and put the result of the future task.
 *
 * @param source The template source./*from  w  ww .ja  va  2s .  co  m*/
 * @param futureTask The future task.
 * @return The resulting value.
 */
private Future<Pair<TemplateSource, Template>> putIfAbsent(final TemplateSource source,
        final FutureTask<Pair<TemplateSource, Template>> futureTask) {
    Future<Pair<TemplateSource, Template>> future = cache.putIfAbsent(source, futureTask);
    if (future == null) {
        future = futureTask;
        futureTask.run();
    }
    return future;
}

From source file:org.b3log.latke.urlfetch.bae.BAEURLFetchService.java

/**
 * {@inheritDoc}//from   w  w w  .j  a v a 2  s  .  c  o  m
 * 
 * <p>
 * <b>Note</b>: Dose <em>NOT</em> support async URL fetch at present, calls this method is equivalent to call 
 * {@link #fetch(org.b3log.latke.urlfetch.HTTPRequest)}.
 * </p>
 */
@Override
public Future<?> fetchAsync(final HTTPRequest request) {
    final FutureTask<HTTPResponse> futureTask = new FutureTask<HTTPResponse>(new Callable<HTTPResponse>() {
        @Override
        public HTTPResponse call() throws Exception {
            return fetch(request);
        }
    });

    // no pool
    futureTask.run();

    return futureTask;
}

From source file:com.alibaba.dragoon.common.protocol.DragoonSession.java

private void handleResponse(ResponseMessage response) {
    int frameId = response.getFrameId();

    ResponseMessageTask task = taskMap.remove(frameId);

    if (task == null) {
        LOG.warn("error frame " + frameId);
        return;/*www.  ja  va 2s .  c  om*/
    }

    if (response.getError() != null) {
        // TODO SET error
        task.setError(new DragoonProtocolException(response.getError()));
    } else {
        task.setResponse(response);
    }

    FutureTask<ResponseMessage> future = futureMap.remove(frameId);

    if (future == null) {
        LOG.warn("error frame " + frameId);
        return;
    }

    future.run();
}

From source file:android.support.test.espresso.base.ThreadPoolExecutorExtractor.java

private <T> FutureTask<T> runOnMainThread(final FutureTask<T> futureToRun) {
    if (Looper.myLooper() != Looper.getMainLooper()) {
        final CountDownLatch latch = new CountDownLatch(1);
        mainHandler.post(new Runnable() {
            @Override//from  w w w  .j  ava  2 s. co m
            public void run() {
                try {
                    futureToRun.run();
                } finally {
                    latch.countDown();
                }
            }
        });
        try {
            latch.await();
        } catch (InterruptedException ie) {
            if (!futureToRun.isDone()) {
                throw new RuntimeException("Interrupted while waiting for task to complete.");
            }
        }
    } else {
        futureToRun.run();
    }

    return futureToRun;
}