Remove most of atomix.utils.*
[controller.git] / third-party / atomix / utils / src / main / java / io / atomix / utils / concurrent / ComposableFuture.java
1 /*
2  * Copyright 2015-present Open Networking Foundation
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package io.atomix.utils.concurrent;
17
18 import java.util.concurrent.CompletableFuture;
19 import java.util.concurrent.Executor;
20 import java.util.function.BiConsumer;
21 import java.util.function.Consumer;
22
23 /**
24  * Special implementation of {@link CompletableFuture} with missing utility methods.
25  *
26  * @author <a href="http://github.com/kuujo">Jordan Halterman</a>
27  */
28 public class ComposableFuture<T> extends CompletableFuture<T> implements BiConsumer<T, Throwable> {
29
30   @Override
31   public void accept(T result, Throwable error) {
32     if (error == null) {
33       complete(result);
34     } else {
35       completeExceptionally(error);
36     }
37   }
38
39   /**
40    * Sets a consumer to be called when the future is failed.
41    *
42    * @param consumer The consumer to call.
43    * @return A new future.
44    */
45   public CompletableFuture<T> except(Consumer<Throwable> consumer) {
46     return whenComplete((result, error) -> {
47       if (error != null) {
48         consumer.accept(error);
49       }
50     });
51   }
52
53   /**
54    * Sets a consumer to be called asynchronously when the future is failed.
55    *
56    * @param consumer The consumer to call.
57    * @return A new future.
58    */
59   public CompletableFuture<T> exceptAsync(Consumer<Throwable> consumer) {
60     return whenCompleteAsync((result, error) -> {
61       if (error != null) {
62         consumer.accept(error);
63       }
64     });
65   }
66
67   /**
68    * Sets a consumer to be called asynchronously when the future is failed.
69    *
70    * @param consumer The consumer to call.
71    * @param executor The executor with which to call the consumer.
72    * @return A new future.
73    */
74   public CompletableFuture<T> exceptAsync(Consumer<Throwable> consumer, Executor executor) {
75     return whenCompleteAsync((result, error) -> {
76       if (error != null) {
77         consumer.accept(error);
78       }
79     }, executor);
80   }
81
82 }