use of ratpack.exec.internal.DefaultPromise in project ratpack by ratpack.
the class Blocking method get.
/**
* Performs a blocking operation on a separate thread, returning a promise for its value.
* <p>
* This method should be used to perform blocking IO, or to perform any operation that synchronously waits for something to happen.
* The given factory function will be executed on a thread from a special pool for such operations (i.e. not a thread from the main compute event loop).
* <p>
* The operation should do as little computation as possible.
* It should just perform the blocking operation and immediately return the result.
* Performing computation during the operation will degrade performance.
*
* @param factory the operation that blocks
* @param <T> the type of value created by the operation
* @return a promise for the return value of the given blocking operation
*/
public static <T> Promise<T> get(Factory<T> factory) {
return new DefaultPromise<>(downstream -> {
DefaultExecution execution = DefaultExecution.require();
EventLoop eventLoop = execution.getEventLoop();
execution.delimit(downstream::error, continuation -> eventLoop.execute(() -> CompletableFuture.supplyAsync(new Supplier<Result<T>>() {
Result<T> result;
@Override
public Result<T> get() {
try {
DefaultExecution.THREAD_BINDING.set(execution);
intercept(execution, execution.getAllInterceptors().iterator(), () -> {
try {
result = Result.success(factory.create());
} catch (Throwable e) {
result = Result.error(e);
}
});
return result;
} catch (Throwable e) {
DefaultExecution.interceptorError(e);
return result;
} finally {
DefaultExecution.THREAD_BINDING.remove();
}
}
}, execution.getController().getBlockingExecutor()).thenAcceptAsync(v -> continuation.resume(() -> downstream.accept(v)), eventLoop)));
});
}
Aggregations