群友分享的一个 es 的 key lock 工具

    1. /**
    2. * @author tys
    3. * @version 1.0
    4. * @date 2022/8/18 5:00 PM
    5. */
    6. /*
    7. * Licensed to Elasticsearch under one or more contributor
    8. * license agreements. See the NOTICE file distributed with
    9. * this work for additional information regarding copyright
    10. * ownership. Elasticsearch licenses this file to you under
    11. * the Apache License, Version 2.0 (the "License"); you may
    12. * not use this file except in compliance with the License.
    13. * You may obtain a copy of the License at
    14. *
    15. * http://www.apache.org/licenses/LICENSE-2.0
    16. *
    17. * Unless required by applicable law or agreed to in writing,
    18. * software distributed under the License is distributed on an
    19. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    20. * KIND, either express or implied. See the License for the
    21. * specific language governing permissions and limitations
    22. * under the License.
    23. */
    24. import org.elasticsearch.common.lease.Releasable;
    25. import org.elasticsearch.common.util.concurrent.ConcurrentCollections;
    26. import java.util.concurrent.ConcurrentMap;
    27. import java.util.concurrent.atomic.AtomicBoolean;
    28. import java.util.concurrent.atomic.AtomicInteger;
    29. import java.util.concurrent.locks.ReentrantLock;
    30. /**
    31. * This class manages locks. Locks can be accessed with an identifier and are
    32. * created the first time they are acquired and removed if no thread hold the
    33. * lock. The latter is important to assure that the list of locks does not grow
    34. * infinitely.
    35. * Note: this lock is reentrant
    36. *
    37. * */
    38. public final class KeyedLock<T> {
    39. private final ConcurrentMap<T, KeyLock> map = ConcurrentCollections.newConcurrentMapWithAggressiveConcurrency();
    40. private final boolean fair;
    41. /**
    42. * Creates a new lock
    43. * @param fair Use fair locking, ie threads get the lock in the order they requested it
    44. */
    45. public KeyedLock(boolean fair) {
    46. this.fair = fair;
    47. }
    48. /**
    49. * Creates a non-fair lock
    50. */
    51. public KeyedLock() {
    52. this(false);
    53. }
    54. /**
    55. * Acquires a lock for the given key. The key is compared by it's equals method not by object identity. The lock can be acquired
    56. * by the same thread multiple times. The lock is released by closing the returned {@link Releasable}.
    57. */
    58. public Releasable acquire(T key) {
    59. while (true) {
    60. KeyLock perNodeLock = map.get(key);
    61. if (perNodeLock == null) {
    62. ReleasableLock newLock = tryCreateNewLock(key);
    63. if (newLock != null) {
    64. return newLock;
    65. }
    66. } else {
    67. assert perNodeLock != null;
    68. int i = perNodeLock.count.get();
    69. if (i > 0 && perNodeLock.count.compareAndSet(i, i + 1)) {
    70. perNodeLock.lock();
    71. return new ReleasableLock(key, perNodeLock);
    72. }
    73. }
    74. }
    75. }
    76. /**
    77. * Tries to acquire the lock for the given key and returns it. If the lock can't be acquired null is returned.
    78. */
    79. public Releasable tryAcquire(T key) {
    80. final KeyLock perNodeLock = map.get(key);
    81. if (perNodeLock == null) {
    82. return tryCreateNewLock(key);
    83. }
    84. if (perNodeLock.tryLock()) { // ok we got it - make sure we increment it accordingly otherwise release it again
    85. int i;
    86. while ((i = perNodeLock.count.get()) > 0) {
    87. // we have to do this in a loop here since even if the count is > 0
    88. // there could be a concurrent blocking acquire that changes the count and then this CAS fails. Since we already got
    89. // the lock we should retry and see if we can still get it or if the count is 0. If that is the case and we give up.
    90. if (perNodeLock.count.compareAndSet(i, i + 1)) {
    91. return new ReleasableLock(key, perNodeLock);
    92. }
    93. }
    94. perNodeLock.unlock(); // make sure we unlock and don't leave the lock in a locked state
    95. }
    96. return null;
    97. }
    98. private ReleasableLock tryCreateNewLock(T key) {
    99. KeyLock newLock = new KeyLock(fair);
    100. newLock.lock();
    101. KeyLock keyLock = map.putIfAbsent(key, newLock);
    102. if (keyLock == null) {
    103. return new ReleasableLock(key, newLock);
    104. }
    105. return null;
    106. }
    107. /**
    108. * Returns <code>true</code> iff the caller thread holds the lock for the given key
    109. */
    110. public boolean isHeldByCurrentThread(T key) {
    111. KeyLock lock = map.get(key);
    112. if (lock == null) {
    113. return false;
    114. }
    115. return lock.isHeldByCurrentThread();
    116. }
    117. private void release(T key, KeyLock lock) {
    118. assert lock == map.get(key);
    119. final int decrementAndGet = lock.count.decrementAndGet();
    120. lock.unlock();
    121. if (decrementAndGet == 0) {
    122. map.remove(key, lock);
    123. }
    124. assert decrementAndGet >= 0 : decrementAndGet + " must be >= 0 but wasn't";
    125. }
    126. private final class ReleasableLock implements Releasable {
    127. final T key;
    128. final KeyLock lock;
    129. final AtomicBoolean closed = new AtomicBoolean();
    130. private ReleasableLock(T key, KeyLock lock) {
    131. this.key = key;
    132. this.lock = lock;
    133. }
    134. @Override
    135. public void close() {
    136. if (closed.compareAndSet(false, true)) {
    137. release(key, lock);
    138. }
    139. }
    140. }
    141. @SuppressWarnings("serial")
    142. private static final class KeyLock extends ReentrantLock {
    143. KeyLock(boolean fair) {
    144. super(fair);
    145. }
    146. private final AtomicInteger count = new AtomicInteger(1);
    147. }
    148. /**
    149. * Returns <code>true</code> if this lock has at least one locked key.
    150. */
    151. public boolean hasLockedKeys() {
    152. return map.isEmpty() == false;
    153. }
    154. }

    重点总结:

    1. ConcurrentMap.putIfAbsent用于 keylock 的创建
    2. AtomicInteger.compareAndSet 用于在同步阻塞获取锁的时候,判定哪一个线程能获取到锁
    3. 释放锁的时候,根据 AtomicInteger 的值判定,如果等于 0 的时候,就从 map 中移除锁