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 package org.apache.hadoop.hbase.client; 19 20 import org.apache.hadoop.classification.InterfaceAudience; 21 import org.apache.hadoop.classification.InterfaceStability; 22 import org.apache.hadoop.hbase.HConstants; 23 24 import java.util.Random; 25 26 /** 27 * Utility used by client connections such as {@link HConnection} and 28 * {@link ServerCallable} 29 */ 30 @InterfaceAudience.Public 31 @InterfaceStability.Evolving 32 public class ConnectionUtils { 33 34 private static final Random RANDOM = new Random(); 35 /** 36 * Calculate pause time. 37 * Built on {@link HConstants#RETRY_BACKOFF}. 38 * @param pause 39 * @param tries 40 * @return How long to wait after <code>tries</code> retries 41 */ 42 public static long getPauseTime(final long pause, final int tries) { 43 int ntries = tries; 44 if (ntries >= HConstants.RETRY_BACKOFF.length) { 45 ntries = HConstants.RETRY_BACKOFF.length - 1; 46 } 47 48 long normalPause = pause * HConstants.RETRY_BACKOFF[ntries]; 49 long jitter = (long)(normalPause * RANDOM.nextFloat() * 0.01f); // 1% possible jitter 50 return normalPause + jitter; 51 } 52 53 54 /** 55 * Adds / subs a 10% jitter to a pause time. Minimum is 1. 56 * @param pause the expected pause. 57 * @param jitter the jitter ratio, between 0 and 1, exclusive. 58 */ 59 public static long addJitter(final long pause, final float jitter) { 60 float lag = pause * (RANDOM.nextFloat() - 0.5f) * jitter; 61 long newPause = pause + (long) lag; 62 if (newPause <= 0) { 63 return 1; 64 } 65 return newPause; 66 } 67 }