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 com.google.protobuf.RpcCallback; 22 import org.apache.hadoop.classification.InterfaceAudience; 23 import org.apache.hadoop.classification.InterfaceStability; 24 25 import java.io.IOException; 26 import java.io.InterruptedIOException; 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.Public 35 @InterfaceStability.Evolving 36 public class BlockingRpcCallback<R> implements RpcCallback<R> { 37 private R result; 38 private boolean resultSet = false; 39 40 /** 41 * Called on completion of the RPC call with the response object, or {@code null} in the case of 42 * an error. 43 * @param parameter the response object or {@code null} if an error occurred 44 */ 45 @Override 46 public void run(R parameter) { 47 synchronized (this) { 48 result = parameter; 49 resultSet = true; 50 this.notify(); 51 } 52 } 53 54 /** 55 * Returns the parameter passed to {@link #run(Object)} or {@code null} if a null value was 56 * passed. When used asynchronously, this method will block until the {@link #run(Object)} 57 * method has been called. 58 * @return the response object or {@code null} if no response was passed 59 */ 60 public synchronized R get() throws IOException { 61 while (!resultSet) { 62 try { 63 this.wait(); 64 } catch (InterruptedException ie) { 65 Thread.currentThread().interrupt(); 66 InterruptedIOException exception = new InterruptedIOException(ie.getMessage()); 67 exception.initCause(ie); 68 throw exception; 69 } 70 } 71 return result; 72 } 73 }