1 /* 2 * Licensed to the Apache Software Foundation (ASF) under one 3 * or more contributor license agreements. See the NOTICE file 4 * distributed with this work for additional information 5 * regarding copyright ownership. The ASF licenses this file 6 * to you under the Apache License, Version 2.0 (the 7 * "License"); you may not use this file except in compliance 8 * with the License. You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, software 13 * distributed under the License is distributed on an "AS IS" BASIS, 14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 * See the License for the specific language governing permissions and 16 * limitations under the License. 17 */ 18 19 package org.apache.hadoop.hbase.ipc; 20 21 import java.io.IOException; 22 import java.io.InterruptedIOException; 23 24 import org.apache.hadoop.hbase.classification.InterfaceAudience; 25 26 import com.google.protobuf.RpcCallback; 27 28 /** 29 * Simple {@link RpcCallback} implementation providing a 30 * {@link java.util.concurrent.Future}-like {@link BlockingRpcCallback#get()} method, which 31 * will block util the instance's {@link BlockingRpcCallback#run(Object)} method has been called. 32 * {@code R} is the RPC response type that will be passed to the {@link #run(Object)} method. 33 */ 34 @InterfaceAudience.Private 35 public class BlockingRpcCallback<R> implements RpcCallback<R> { 36 private R result; 37 private boolean resultSet = false; 38 39 /** 40 * Called on completion of the RPC call with the response object, or {@code null} in the case of 41 * an error. 42 * @param parameter the response object or {@code null} if an error occurred 43 */ 44 @Override 45 public void run(R parameter) { 46 synchronized (this) { 47 result = parameter; 48 resultSet = true; 49 this.notify(); 50 } 51 } 52 53 /** 54 * Returns the parameter passed to {@link #run(Object)} or {@code null} if a null value was 55 * passed. When used asynchronously, this method will block until the {@link #run(Object)} 56 * method has been called. 57 * @return the response object or {@code null} if no response was passed 58 */ 59 public synchronized R get() throws IOException { 60 while (!resultSet) { 61 try { 62 this.wait(); 63 } catch (InterruptedException ie) { 64 InterruptedIOException exception = new InterruptedIOException(ie.getMessage()); 65 exception.initCause(ie); 66 throw exception; 67 } 68 } 69 return result; 70 } 71 }