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.TimeUnit;
031import org.apache.hadoop.hbase.HBaseClassTestRule;
032import org.apache.hadoop.hbase.testclassification.MediumTests;
033import org.apache.hadoop.hbase.testclassification.MiscTests;
034import org.junit.ClassRule;
035import org.junit.Test;
036import org.junit.experimental.categories.Category;
037import org.slf4j.Logger;
038import org.slf4j.LoggerFactory;
039
040@Category({MiscTests.class, MediumTests.class})
041// Medium as it creates 100 threads; seems better to run it isolated
042public class TestIdLock {
043
044  @ClassRule
045  public static final HBaseClassTestRule CLASS_RULE =
046      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 = new Random();
070      long endTime = System.currentTimeMillis() + NUM_SECONDS * 1000;
071      while (System.currentTimeMillis() < 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 + ", "
080                + clientId + " failed");
081            return false;
082          }
083
084          idOwner.put(id, clientId);
085          Thread.sleep(sleepMs);
086          idOwner.remove(id);
087
088        } finally {
089          idLock.releaseLockEntry(lockEntry);
090        }
091      }
092      return true;
093    }
094
095  }
096
097  @Test
098  public void testMultipleClients() throws Exception {
099    ExecutorService exec = Executors.newFixedThreadPool(NUM_THREADS);
100    try {
101      ExecutorCompletionService<Boolean> ecs = new ExecutorCompletionService<>(exec);
102      for (int i = 0; i < NUM_THREADS; ++i)
103        ecs.submit(new IdLockTestThread("client_" + i));
104      for (int i = 0; i < NUM_THREADS; ++i) {
105        Future<Boolean> result = ecs.take();
106        assertTrue(result.get());
107      }
108      idLock.assertMapEmpty();
109    } finally {
110      exec.shutdown();
111      exec.awaitTermination(5000, TimeUnit.MILLISECONDS);
112    }
113  }
114
115
116}
117