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