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.util;
020
021import java.io.IOException;
022import java.io.InterruptedIOException;
023import java.util.concurrent.ConcurrentHashMap;
024import java.util.concurrent.ConcurrentMap;
025
026import org.apache.yetus.audience.InterfaceAudience;
027
028import org.apache.hbase.thirdparty.com.google.common.annotations.VisibleForTesting;
029
030/**
031 * Allows multiple concurrent clients to lock on a numeric id with a minimal
032 * memory overhead. The intended usage is as follows:
033 *
034 * <pre>
035 * IdLock.Entry lockEntry = idLock.getLockEntry(id);
036 * try {
037 *   // User code.
038 * } finally {
039 *   idLock.releaseLockEntry(lockEntry);
040 * }</pre>
041 */
042@InterfaceAudience.Private
043public class IdLock {
044
045  /** An entry returned to the client as a lock object */
046  public static class Entry {
047    private final long id;
048    private int numWaiters;
049    private boolean locked = true;
050
051    private Entry(long id) {
052      this.id = id;
053    }
054
055    @Override
056    public String toString() {
057      return "id=" + id + ", numWaiter=" + numWaiters + ", isLocked="
058          + locked;
059    }
060  }
061
062  private ConcurrentMap<Long, Entry> map = new ConcurrentHashMap<>();
063
064  /**
065   * Blocks until the lock corresponding to the given id is acquired.
066   *
067   * @param id an arbitrary number to lock on
068   * @return an "entry" to pass to {@link #releaseLockEntry(Entry)} to release
069   *         the lock
070   * @throws IOException if interrupted
071   */
072  public Entry getLockEntry(long id) throws IOException {
073    Entry entry = new Entry(id);
074    Entry existing;
075    while ((existing = map.putIfAbsent(entry.id, entry)) != null) {
076      synchronized (existing) {
077        if (existing.locked) {
078          ++existing.numWaiters;  // Add ourselves to waiters.
079          while (existing.locked) {
080            try {
081              existing.wait();
082            } catch (InterruptedException e) {
083              --existing.numWaiters;  // Remove ourselves from waiters.
084              throw new InterruptedIOException(
085                  "Interrupted waiting to acquire sparse lock");
086            }
087          }
088
089          --existing.numWaiters;  // Remove ourselves from waiters.
090          existing.locked = true;
091          return existing;
092        }
093        // If the entry is not locked, it might already be deleted from the
094        // map, so we cannot return it. We need to get our entry into the map
095        // or get someone else's locked entry.
096      }
097    }
098    return entry;
099  }
100
101  /**
102   * Must be called in a finally block to decrease the internal counter and
103   * remove the monitor object for the given id if the caller is the last
104   * client.
105   *
106   * @param entry the return value of {@link #getLockEntry(long)}
107   */
108  public void releaseLockEntry(Entry entry) {
109    synchronized (entry) {
110      entry.locked = false;
111      if (entry.numWaiters > 0) {
112        entry.notify();
113      } else {
114        map.remove(entry.id);
115      }
116    }
117  }
118
119  /** For testing */
120  void assertMapEmpty() {
121    assert map.isEmpty();
122  }
123
124  @VisibleForTesting
125  public void waitForWaiters(long id, int numWaiters) throws InterruptedException {
126    for (Entry entry;;) {
127      entry = map.get(id);
128      if (entry != null) {
129        synchronized (entry) {
130          if (entry.numWaiters >= numWaiters) {
131            return;
132          }
133        }
134      }
135      Thread.sleep(100);
136    }
137  }
138}