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.util;
019
020import static org.junit.Assert.assertTrue;
021
022import java.util.Map;
023import java.util.Random;
024import java.util.concurrent.Callable;
025import java.util.concurrent.ConcurrentHashMap;
026import java.util.concurrent.ExecutorCompletionService;
027import java.util.concurrent.ExecutorService;
028import java.util.concurrent.Executors;
029import java.util.concurrent.Future;
030import java.util.concurrent.ThreadLocalRandom;
031import java.util.concurrent.TimeUnit;
032import org.apache.hadoop.hbase.HBaseClassTestRule;
033import org.apache.hadoop.hbase.testclassification.MediumTests;
034import org.apache.hadoop.hbase.testclassification.MiscTests;
035import org.junit.ClassRule;
036import org.junit.Test;
037import org.junit.experimental.categories.Category;
038import org.slf4j.Logger;
039import org.slf4j.LoggerFactory;
040
041@Category({ MiscTests.class, MediumTests.class })
042// Medium as it creates 100 threads; seems better to run it isolated
043public class TestIdLock {
044
045  @ClassRule
046  public static final HBaseClassTestRule CLASS_RULE = HBaseClassTestRule.forClass(TestIdLock.class);
047
048  private static final Logger LOG = LoggerFactory.getLogger(TestIdLock.class);
049
050  private static final int NUM_IDS = 16;
051  private static final int NUM_THREADS = 128;
052  private static final int NUM_SECONDS = 15;
053
054  private IdLock idLock = new IdLock();
055
056  private Map<Long, String> idOwner = new ConcurrentHashMap<>();
057
058  private class IdLockTestThread implements Callable<Boolean> {
059
060    private String clientId;
061
062    public IdLockTestThread(String clientId) {
063      this.clientId = clientId;
064    }
065
066    @Override
067    public Boolean call() throws Exception {
068      Thread.currentThread().setName(clientId);
069      Random rand = ThreadLocalRandom.current();
070      long endTime = EnvironmentEdgeManager.currentTime() + NUM_SECONDS * 1000;
071      while (EnvironmentEdgeManager.currentTime() < endTime) {
072        long id = rand.nextInt(NUM_IDS);
073
074        IdLock.Entry lockEntry = idLock.getLockEntry(id);
075        try {
076          int sleepMs = 1 + rand.nextInt(4);
077          String owner = idOwner.get(id);
078          if (owner != null) {
079            LOG.error("Id " + id + " already taken by " + owner + ", " + clientId + " failed");
080            return false;
081          }
082
083          idOwner.put(id, clientId);
084          Thread.sleep(sleepMs);
085          idOwner.remove(id);
086
087        } finally {
088          idLock.releaseLockEntry(lockEntry);
089        }
090      }
091      return true;
092    }
093
094  }
095
096  @Test
097  public void testMultipleClients() throws Exception {
098    ExecutorService exec = Executors.newFixedThreadPool(NUM_THREADS);
099    try {
100      ExecutorCompletionService<Boolean> ecs = new ExecutorCompletionService<>(exec);
101      for (int i = 0; i < NUM_THREADS; ++i)
102        ecs.submit(new IdLockTestThread("client_" + i));
103      for (int i = 0; i < NUM_THREADS; ++i) {
104        Future<Boolean> result = ecs.take();
105        assertTrue(result.get());
106      }
107      idLock.assertMapEmpty();
108    } finally {
109      exec.shutdown();
110      exec.awaitTermination(5000, TimeUnit.MILLISECONDS);
111    }
112  }
113
114}