001/* 002 * Copyright 2002-2018 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * https://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package org.springframework.util.concurrent; 018 019import java.util.concurrent.CompletableFuture; 020import java.util.concurrent.Future; 021 022/** 023 * Extend {@link Future} with the capability to accept completion callbacks. 024 * If the future has completed when the callback is added, the callback is 025 * triggered immediately. 026 * 027 * <p>Inspired by {@code com.google.common.util.concurrent.ListenableFuture}. 028 * 029 * @author Arjen Poutsma 030 * @author Sebastien Deleuze 031 * @author Juergen Hoeller 032 * @since 4.0 033 * @param <T> the result type returned by this Future's {@code get} method 034 */ 035public interface ListenableFuture<T> extends Future<T> { 036 037 /** 038 * Register the given {@code ListenableFutureCallback}. 039 * @param callback the callback to register 040 */ 041 void addCallback(ListenableFutureCallback<? super T> callback); 042 043 /** 044 * Java 8 lambda-friendly alternative with success and failure callbacks. 045 * @param successCallback the success callback 046 * @param failureCallback the failure callback 047 * @since 4.1 048 */ 049 void addCallback(SuccessCallback<? super T> successCallback, FailureCallback failureCallback); 050 051 052 /** 053 * Expose this {@link ListenableFuture} as a JDK {@link CompletableFuture}. 054 * @since 5.0 055 */ 056 default CompletableFuture<T> completable() { 057 CompletableFuture<T> completable = new DelegatingCompletableFuture<>(this); 058 addCallback(completable::complete, completable::completeExceptionally); 059 return completable; 060 } 061 062}