001/**
002 *
003 * Licensed to the Apache Software Foundation (ASF) under one
004 * or more contributor license agreements.  See the NOTICE file
005 * distributed with this work for additional information
006 * regarding copyright ownership.  The ASF licenses this file
007 * to you under the Apache License, Version 2.0 (the
008 * "License"); you may not use this file except in compliance
009 * with the License.  You may obtain a copy of the License at
010 *
011 *     http://www.apache.org/licenses/LICENSE-2.0
012 *
013 * Unless required by applicable law or agreed to in writing, software
014 * distributed under the License is distributed on an "AS IS" BASIS,
015 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
016 * See the License for the specific language governing permissions and
017 * limitations under the License.
018 */
019package org.apache.hadoop.hbase.client;
020
021import java.util.Arrays;
022import java.util.Random;
023
024import org.apache.hadoop.hbase.HConstants;
025import org.apache.yetus.audience.InterfaceAudience;
026
027/**
028 * NonceGenerator implementation that uses client ID hash + random int as nonce group, and random
029 * numbers as nonces.
030 */
031@InterfaceAudience.Private
032public final class PerClientRandomNonceGenerator implements NonceGenerator {
033
034  private static final PerClientRandomNonceGenerator INST = new PerClientRandomNonceGenerator();
035
036  private final Random rdm = new Random();
037  private final long clientId;
038
039  private PerClientRandomNonceGenerator() {
040    byte[] clientIdBase = ClientIdGenerator.generateClientId();
041    this.clientId = (((long) Arrays.hashCode(clientIdBase)) << 32) + rdm.nextInt();
042  }
043
044  @Override
045  public long getNonceGroup() {
046    return this.clientId;
047  }
048
049  @Override
050  public long newNonce() {
051    long result = HConstants.NO_NONCE;
052    do {
053      result = rdm.nextLong();
054    } while (result == HConstants.NO_NONCE);
055    return result;
056  }
057
058  /**
059   * Get the singleton nonce generator.
060   */
061  public static PerClientRandomNonceGenerator get() {
062    return INST;
063  }
064}