001/** 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, software 013 * distributed under the License is distributed on an "AS IS" BASIS, 014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 015 * See the License for the specific language governing permissions and 016 * limitations under the License. 017 */ 018package org.apache.hadoop.hbase.util; 019 020import java.util.concurrent.CompletableFuture; 021import java.util.function.BiConsumer; 022import org.apache.yetus.audience.InterfaceAudience; 023import org.slf4j.Logger; 024import org.slf4j.LoggerFactory; 025 026/** 027 * Helper class for processing futures. 028 */ 029@InterfaceAudience.Private 030public final class FutureUtils { 031 032 private static final Logger LOG = LoggerFactory.getLogger(FutureUtils.class); 033 034 private FutureUtils() { 035 } 036 037 /** 038 * This is method is used when you just want to add a listener to the given future. We will call 039 * {@link CompletableFuture#whenComplete(BiConsumer)} to register the {@code action} to the 040 * {@code future}. Ignoring the return value of a Future is considered as a bad practice as it may 041 * suppress exceptions thrown from the code that completes the future, and this method will catch 042 * all the exception thrown from the {@code action} to catch possible code bugs. 043 * <p/> 044 * And the error phone check will always report FutureReturnValueIgnored because every method in 045 * the {@link CompletableFuture} class will return a new {@link CompletableFuture}, so you always 046 * have one future that has not been checked. So we introduce this method and add a suppress 047 * warnings annotation here. 048 */ 049 @SuppressWarnings("FutureReturnValueIgnored") 050 public static <T> void addListener(CompletableFuture<T> future, 051 BiConsumer<? super T, ? super Throwable> action) { 052 future.whenComplete((resp, error) -> { 053 try { 054 action.accept(resp, error); 055 } catch (Throwable t) { 056 LOG.error("Unexpected error caught when processing CompletableFuture", t); 057 } 058 }); 059 } 060}