View Javadoc

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