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

io.atomix.catalyst.concurrent.ComposableFuture Maven / Gradle / Ivy

The newest version!
/*
 * Copyright 2015 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.atomix.catalyst.concurrent;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.function.BiConsumer;
import java.util.function.Consumer;

/**
 * Special implementation of {@link java.util.concurrent.CompletableFuture} with missing utility methods.
 *
 * @author Jordan Halterman
 */
public class ComposableFuture extends CompletableFuture implements BiConsumer {

  @Override
  public void accept(T result, Throwable error) {
    if (error == null) {
      complete(result);
    } else {
      completeExceptionally(error);
    }
  }

  /**
   * Sets a consumer to be called when the future is failed.
   *
   * @param consumer The consumer to call.
   * @return A new future.
   */
  public CompletableFuture except(Consumer consumer) {
    return whenComplete((result, error) -> {
      if (error != null) {
        consumer.accept(error);
      }
    });
  }

  /**
   * Sets a consumer to be called asynchronously when the future is failed.
   *
   * @param consumer The consumer to call.
   * @return A new future.
   */
  public CompletableFuture exceptAsync(Consumer consumer) {
    return whenCompleteAsync((result, error) -> {
      if (error != null) {
        consumer.accept(error);
      }
    });
  }

  /**
   * Sets a consumer to be called asynchronously when the future is failed.
   *
   * @param consumer The consumer to call.
   * @param executor The executor with which to call the consumer.
   * @return A new future.
   */
  public CompletableFuture exceptAsync(Consumer consumer, Executor executor) {
    return whenCompleteAsync((result, error) -> {
      if (error != null) {
        consumer.accept(error);
      }
    }, executor);
  }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy