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