All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.ea.orbit.concurrent.Task Maven / Gradle / Ivy

The newest version!
/*
 Copyright (C) 2015 Electronic Arts Inc.  All rights reserved.

 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions
 are met:

 1.  Redistributions of source code must retain the above copyright
     notice, this list of conditions and the following disclaimer.
 2.  Redistributions in binary form must reproduce the above copyright
     notice, this list of conditions and the following disclaimer in the
     documentation and/or other materials provided with the distribution.
 3.  Neither the name of Electronic Arts, Inc. ("EA") nor the names of
     its contributors may be used to endorse or promote products derived
     from this software without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY ELECTRONIC ARTS AND ITS CONTRIBUTORS "AS IS" AND ANY
 EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 DISCLAIMED. IN NO EVENT SHALL ELECTRONIC ARTS OR ITS CONTRIBUTORS BE LIABLE FOR ANY
 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package com.ea.orbit.concurrent;

import java.util.Collection;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Task are CompletableFutures were with a few changes.
 * 

*

    *
  • complete and completeExceptionally are not publicly accessible.
  • *
  • few utility methods (thenRun, thenReturn)
  • *
  • TODO: all callbacks are async by default using the current executor
  • *
*

* * @param the type of the returned object. * @see java.util.concurrent.CompletableFuture */ public class Task extends CompletableFuture { private static Void NIL = null; private static Executor commonPool = ExecutorUtils.newScalingThreadPool(100); private static final ScheduledExecutorService schedulerExecutor = Executors.newScheduledThreadPool(10); // TODO: make all callbacks async by default and using the current executor // what "current executor' means will have to be defined. // the idea is to use a framework supplied executor to serve // single point to capture all activity derived from the execution // of one application request. // Including logs, stats, exception and timing information. // TODO: consider creating a public class CTask = "Completable Task" /** * Creates an already completed task from the given value. * * @param value the value to be wrapped with a task */ public static Task fromValue(T value) { final Task t = new Task<>(); t.internalComplete(value); return t; } public static Task fromException(Throwable ex) { final Task t = new Task<>(); t.internalCompleteExceptionally(ex); return t; } protected boolean internalComplete(T value) { return super.complete(value); } protected boolean internalCompleteExceptionally(Throwable ex) { return super.completeExceptionally(ex); } /** * This completableFuture derived method is not available for Tasks. */ @Override @Deprecated public boolean complete(T value) { // TODO: throw an exception return super.complete(value); } /** * This completableFuture derived method is not available for Tasks. */ @Override @Deprecated public boolean completeExceptionally(Throwable ex) { // TODO: throw an exception return super.completeExceptionally(ex); } /** * Wraps a CompletionStage as a Task or just casts it if it is already a Task. * * @param stage the stage to be wrapped or casted to Task * @return stage cast as Task of a new Task that is dependent on the completion of that stage. */ public static Task from(CompletionStage stage) { if (stage instanceof Task) { return (Task) stage; } final Task t = new Task<>(); stage.handle((T v, Throwable ex) -> { if (ex != null) { t.internalCompleteExceptionally(ex); } else { t.internalComplete(v); } return null; }); return t; } /** * Wraps a Future as a Task or just casts it if it is already a Task. *

If future implements CompletionStage CompletionStage.handle will be used.

*

* If future is a plain old future, a runnable will executed using a default task pool. * This runnable will wait on the future using Future.get(timeout,timeUnit), with a timeout of 5ms. * Every time this task times out it will be rescheduled. * Starvation of the pool is prevented by the rescheduling behaviour. *

* * @param future the future to be wrapped or casted to Task * @return future cast as Task of a new Task that is dependent on the completion of that future. */ @SuppressWarnings("unchecked") public static Task fromFuture(Future future) { if (future instanceof Task) { return (Task) future; } if (future instanceof CompletionStage) { return from((CompletionStage) future); } final Task t = new Task<>(); if (future.isDone()) { try { t.internalComplete(future.get()); } catch (Throwable ex) { t.internalCompleteExceptionally(ex); } return t; } // potentially very expensive commonPool.execute(new TaskFutureAdapter<>(t, future, commonPool, 5, TimeUnit.MILLISECONDS)); return t; } /** * Returns a new task that will fail if the original is not completed withing the given timeout. * This doesn't modify the original task in any way. *

* Example: *

Task<String> result = aTask.failAfter(60, TimeUnit.SECONDS);
* * @param timeout the time from now * @param timeUnit the time unit of the timeout parameter * @return a new task */ public Task failAfter(final long timeout, final TimeUnit timeUnit) { final Task t = new Task<>(); // TODO: find a way to inject time for testing // also consider letting the application override this with the TaskContext final ScheduledFuture rr = schedulerExecutor.schedule( () -> { // using t.isDone insteadof this.isDone // because the propagation of this.isDone can be delayed by slow listeners. if (!t.isDone()) { t.internalCompleteExceptionally(new TimeoutException()); } }, timeout, timeUnit); this.handle((T v, Throwable ex) -> { // removing the scheduled timeout to clear some memory rr.cancel(false); if (!t.isDone()) { if (ex != null) { t.internalCompleteExceptionally(ex); } else { t.internalComplete(v); } } return null; }); return t; } /** * Returns a new task that will fail if the original is not completed withing the given timeout. * * @param time the time from now * @param timeUnit the time unit of the timeout parameter * @return a new task */ public static Task sleep(final long time, final TimeUnit timeUnit) { final Task t = new Task<>(); // TODO: find a way to inject time for testing // also consider letting the application override this with the TaskContext final ScheduledFuture rr = schedulerExecutor.schedule( () -> { if (!t.isDone()) { t.internalComplete(null); } }, time, timeUnit); return t; } static class TaskFutureAdapter implements Runnable { Task task; Future future; Executor executor; long waitTimeout; TimeUnit waitTimeoutUnit; public TaskFutureAdapter( final Task task, final Future future, final Executor executor, long waitTimeout, TimeUnit waitTimeoutUnit) { this.task = task; this.future = future; this.executor = executor; this.waitTimeout = waitTimeout; this.waitTimeoutUnit = waitTimeoutUnit; } public void run() { try { while (!task.isDone()) { try { task.internalComplete(future.get(waitTimeout, waitTimeoutUnit)); return; } catch (TimeoutException ex) { if (future.isDone()) { // in this case something completed the future with a timeout exception. try { task.internalComplete(future.get(waitTimeout, waitTimeoutUnit)); return; } catch (Throwable tex0) { task.internalCompleteExceptionally(tex0); } return; } try { // reschedule // potentially very expensive, might limit request throughput executor.execute(this); return; } catch (RejectedExecutionException rex) { // ignoring and continuing. // might potentially worsen an already starving system. // adding the redundant continue here to highlight the code path continue; } catch (Throwable tex) { task.internalCompleteExceptionally(tex); return; } } catch (Throwable ex) { task.internalCompleteExceptionally(ex); return; } } } catch (Throwable ex) { task.internalCompleteExceptionally(ex); } } } public static Task done() { final Task task = new Task<>(); task.internalComplete(NIL); return task; } @Override public Task thenApply(final Function fn) { final Function wrap = TaskContext.wrap(fn); return from(super.thenApply(wrap)); } @Override public Task thenAccept(final Consumer action) { return from(super.thenAccept(TaskContext.wrap(action))); } @Override public Task whenComplete(final BiConsumer action) { return from(super.whenComplete(TaskContext.wrap(action))); } /** * Returns a new Task that is executed when this task completes normally. * The result of the new Task will be the result of the Supplier passed as parameter. *

* See the {@link CompletionStage} documentation for rules * covering exceptional completion. * * @param supplier the Supplier that will provider the value * the returned Task * @param the supplier's return type * @return the new Task */ public Task thenReturn(final Supplier supplier) { // must be separated otherwise the execution of the wrap could happen in another thread final Supplier wrap = TaskContext.wrap(supplier); return from(super.thenApply(x -> wrap.get())); } public Task thenCompose(Function> fn) { final Function> wrap = TaskContext.wrap(fn); return Task.from(super.thenCompose(wrap)); } public Task thenCompose(Supplier> fn) { // must be separated otherwise the execution of the wrap could happen in another thread final Supplier> wrap = TaskContext.wrap(fn); return Task.from(super.thenCompose((T x) -> wrap.get())); } @Override public Task handle(final BiFunction fn) { final BiFunction wrap = TaskContext.wrap(fn); return from(super.handle(wrap)); } @Override public Task exceptionally(final Function fn) { return from(super.exceptionally(TaskContext.wrap(fn))); } @Override public Task thenRun(final Runnable action) { return from(super.thenRun(TaskContext.wrap(action))); } @Override public Task acceptEither(CompletionStage completionStage, Consumer consumer) { final Consumer wrap = TaskContext.wrap(consumer); return Task.from(super.acceptEither(completionStage, wrap)); } @Override public Task acceptEitherAsync(CompletionStage completionStage, Consumer consumer) { final Consumer wrap = TaskContext.wrap(consumer); return Task.from(super.acceptEitherAsync(completionStage, wrap)); } @Override public Task acceptEitherAsync(CompletionStage completionStage, Consumer consumer, Executor executor) { return Task.from(super.acceptEitherAsync(completionStage, TaskContext.wrap(consumer), executor)); } @Override public Task applyToEither(CompletionStage completionStage, Function function) { return Task.from(super.applyToEither(completionStage, TaskContext.wrap(function))); } @Override public Task applyToEitherAsync(CompletionStage completionStage, Function function, Executor executor) { return Task.from(super.applyToEitherAsync(completionStage, TaskContext.wrap(function), executor)); } @Override public Task applyToEitherAsync(CompletionStage completionStage, Function function) { return Task.from(super.applyToEitherAsync(completionStage, TaskContext.wrap(function))); } @Override public Task handleAsync(BiFunction biFunction, Executor executor) { final BiFunction wrap = TaskContext.wrap(biFunction); return Task.from(super.handleAsync(wrap, executor)); } @Override public Task handleAsync(BiFunction biFunction) { final BiFunction wrap = TaskContext.wrap(biFunction); return Task.from(super.handleAsync(wrap)); } @Override public Task runAfterBoth(CompletionStage completionStage, Runnable runnable) { return Task.from(super.runAfterBoth(completionStage, TaskContext.wrap(runnable))); } @Override public Task runAfterBothAsync(CompletionStage completionStage, Runnable runnable) { return Task.from(super.runAfterBothAsync(completionStage, TaskContext.wrap(runnable))); } @Override public Task runAfterBothAsync(CompletionStage completionStage, Runnable runnable, Executor executor) { return Task.from(super.runAfterBothAsync(completionStage, TaskContext.wrap(runnable), executor)); } @Override public Task runAfterEither(CompletionStage completionStage, Runnable runnable) { return Task.from(super.runAfterEither(completionStage, TaskContext.wrap(runnable))); } @Override public Task runAfterEitherAsync(CompletionStage completionStage, Runnable runnable) { return Task.from(super.runAfterEitherAsync(completionStage, TaskContext.wrap(runnable))); } @Override public Task runAfterEitherAsync(CompletionStage completionStage, Runnable runnable, Executor executor) { return Task.from(super.runAfterEitherAsync(completionStage, TaskContext.wrap(runnable), executor)); } public static Task runAsync(Runnable runnable) { return Task.from(CompletableFuture.runAsync(TaskContext.wrap(runnable))); } public static Task runAsync(Runnable runnable, Executor executor) { return Task.from(CompletableFuture.runAsync(TaskContext.wrap(runnable), executor)); } public static Task supplyAsync(TaskSupplier supplier) { return Task.from(CompletableFuture.supplyAsync(TaskContext.wrap(supplier))).thenCompose(t -> t); } public static Task supplyAsync(Supplier supplier) { return Task.from(CompletableFuture.supplyAsync(TaskContext.wrap(supplier))); } public static Task supplyAsync(Supplier supplier, Executor executor) { return Task.from(CompletableFuture.supplyAsync(TaskContext.wrap(supplier), executor)); } public static Task supplyAsync(TaskSupplier supplier, Executor executor) { return Task.from(CompletableFuture.supplyAsync(TaskContext.wrap(supplier), executor).thenCompose(t -> t)); } @Override public Task thenAcceptAsync(Consumer consumer, Executor executor) { return Task.from(super.thenAcceptAsync(TaskContext.wrap(consumer), executor)); } @Override public Task thenAcceptAsync(Consumer consumer) { return Task.from(super.thenAcceptAsync(TaskContext.wrap(consumer))); } @Override public Task thenAcceptBoth(CompletionStage completionStage, BiConsumer biConsumer) { return Task.from(super.thenAcceptBoth(completionStage, TaskContext.wrap(biConsumer))); } @Override public Task thenAcceptBothAsync(CompletionStage completionStage, BiConsumer biConsumer, Executor executor) { return Task.from(super.thenAcceptBothAsync(completionStage, TaskContext.wrap(biConsumer), executor)); } @Override public Task thenAcceptBothAsync(CompletionStage completionStage, BiConsumer biConsumer) { return Task.from(super.thenAcceptBothAsync(completionStage, TaskContext.wrap(biConsumer))); } @Override public Task thenApplyAsync(Function function, Executor executor) { final Function wrap = TaskContext.wrap(function); return Task.from(super.thenApplyAsync(wrap, executor)); } @Override public Task thenApplyAsync(Function function) { final Function wrap = TaskContext.wrap(function); return Task.from(super.thenApplyAsync(wrap)); } @Override public Task thenCombine(CompletionStage completionStage, BiFunction biFunction) { final BiFunction wrap = TaskContext.wrap(biFunction); return Task.from(super.thenCombine(completionStage, wrap)); } @Override public Task thenCombineAsync(CompletionStage completionStage, BiFunction biFunction, Executor executor) { final BiFunction wrap = TaskContext.wrap(biFunction); return Task.from(super.thenCombineAsync(completionStage, wrap, executor)); } @Override public Task thenCombineAsync(CompletionStage completionStage, BiFunction biFunction) { final BiFunction wrap = TaskContext.wrap(biFunction); return Task.from(super.thenCombineAsync(completionStage, wrap)); } @Override public Task thenComposeAsync(Function> function, Executor executor) { final Function> wrap = TaskContext.wrap(function); return Task.from(super.thenComposeAsync(wrap, executor)); } @Override public Task thenComposeAsync(Function> function) { final Function> wrap = TaskContext.wrap(function); return Task.from(super.thenComposeAsync(wrap)); } @Override public Task thenRunAsync(Runnable runnable) { return Task.from(super.thenRunAsync(TaskContext.wrap(runnable))); } @Override public Task thenRunAsync(Runnable runnable, Executor executor) { return Task.from(super.thenRunAsync(TaskContext.wrap(runnable), executor)); } @Override public Task whenCompleteAsync(BiConsumer biConsumer) { return Task.from(super.whenCompleteAsync(TaskContext.wrap(biConsumer))); } @Override public Task whenCompleteAsync(BiConsumer biConsumer, Executor executor) { return Task.from(super.whenCompleteAsync(TaskContext.wrap(biConsumer), executor)); } /** * @throws NullPointerException if the array or any of its elements are * {@code null} */ public static Task allOf(CompletableFuture... cfs) { return from(CompletableFuture.allOf(cfs)); } /** * @throws NullPointerException if the collection or any of its elements are * {@code null} */ public static , C extends Collection> Task allOf(C cfs) { return from(CompletableFuture.allOf(cfs.toArray(new CompletableFuture[cfs.size()]))); } /** * @throws NullPointerException if the stream or any of its elements are * {@code null} */ public static > Task allOf(Stream cfs) { final List futureList = cfs.collect(Collectors.toList()); @SuppressWarnings("rawtypes") final CompletableFuture[] futureArray = futureList.toArray(new CompletableFuture[futureList.size()]); return from(CompletableFuture.allOf(futureArray)); } /** * @throws NullPointerException if the array or any of its elements are * {@code null} */ public static Task anyOf(CompletableFuture... cfs) { return from(CompletableFuture.anyOf(cfs)); } /** * @throws NullPointerException if the collection or any of its elements are * {@code null} */ public static > Task anyOf(Collection cfs) { return from(CompletableFuture.anyOf(cfs.toArray(new CompletableFuture[cfs.size()]))); } /** * @throws NullPointerException if the stream or any of its elements are * {@code null} */ public static > Task anyOf(Stream cfs) { return from(CompletableFuture.anyOf((CompletableFuture[]) cfs.toArray(size -> new CompletableFuture[size]))); } }