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