001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase.regionserver;
019
020import java.util.concurrent.atomic.AtomicInteger;
021import org.apache.hadoop.hbase.ServerName;
022import org.apache.yetus.audience.InterfaceAudience;
023
024import org.apache.hbase.thirdparty.com.google.common.hash.Hashing;
025
026/**
027 * Generate a new style scanner id to prevent collision with previous started server or other RSs.
028 * We have 64 bits to use. The first 32 bits are MurmurHash32 of ServerName string "host,port,ts".
029 * The ServerName contains both host, port, and start timestamp so it can prevent collision. The
030 * lowest 32bit is generated by atomic int.
031 */
032@InterfaceAudience.Private
033public class ScannerIdGenerator {
034
035  private final long serverNameHash;
036  private final AtomicInteger scannerIdGen = new AtomicInteger(0);
037
038  public ScannerIdGenerator(ServerName serverName) {
039    long hash = Hashing.murmur3_32()
040      .hashString(serverName.toString(), java.nio.charset.StandardCharsets.UTF_8).asInt();
041    this.serverNameHash = hash << 32;
042  }
043
044  public long generateNewScannerId() {
045    return (scannerIdGen.incrementAndGet() & 0x00000000FFFFFFFFL) | serverNameHash;
046  }
047
048  public static void main(final String[] args) {
049    ScannerIdGenerator sig = new ScannerIdGenerator(ServerName.valueOf("a.example.org,1234,5678"));
050    for (int i = 0; i < 10; i++) {
051      System.out.println(sig.generateNewScannerId());
052    }
053  }
054}