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.wal;
019
020import static org.apache.hadoop.hbase.util.ConcurrentMapUtils.computeIfAbsent;
021
022import java.util.concurrent.ConcurrentHashMap;
023import java.util.concurrent.atomic.AtomicInteger;
024import org.apache.hadoop.conf.Configuration;
025import org.apache.hadoop.hbase.util.Bytes;
026import org.apache.hadoop.hbase.wal.RegionGroupingProvider.RegionGroupingStrategy;
027import org.apache.yetus.audience.InterfaceAudience;
028
029/**
030 * A WAL grouping strategy that limits the number of wal groups to
031 * "hbase.wal.regiongrouping.numgroups".
032 */
033@InterfaceAudience.Private
034public class BoundedGroupingStrategy implements RegionGroupingStrategy {
035
036  static final String NUM_REGION_GROUPS = "hbase.wal.regiongrouping.numgroups";
037  static final int DEFAULT_NUM_REGION_GROUPS = 2;
038
039  private ConcurrentHashMap<String, String> groupNameCache = new ConcurrentHashMap<>();
040  private AtomicInteger counter = new AtomicInteger(0);
041  private String[] groupNames;
042
043  @Override
044  public String group(byte[] identifier, byte[] namespace) {
045    String idStr = Bytes.toString(identifier);
046    return computeIfAbsent(groupNameCache, idStr,
047      () -> groupNames[getAndIncrAtomicInteger(counter, groupNames.length)]);
048  }
049
050  // Non-blocking incrementing & resetting of AtomicInteger.
051  private int getAndIncrAtomicInteger(AtomicInteger atomicInt, int reset) {
052    for (;;) {
053      int current = atomicInt.get();
054      int next = (current + 1);
055      if (next == reset) {
056        next = 0;
057      }
058      if (atomicInt.compareAndSet(current, next)) return current;
059    }
060  }
061
062  @Override
063  public void init(Configuration config, String providerId) {
064    int regionGroupNumber = config.getInt(NUM_REGION_GROUPS, DEFAULT_NUM_REGION_GROUPS);
065    groupNames = new String[regionGroupNumber];
066    for (int i = 0; i < regionGroupNumber; i++) {
067      groupNames[i] = providerId + GROUP_NAME_DELIMITER + "regiongroup-" + i;
068    }
069  }
070
071}