001/*
002 * Copyright (C) 2011 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.util.concurrent;
016
017import static com.google.common.collect.Lists.newArrayList;
018import static java.util.Arrays.sort;
019import static java.util.Collections.unmodifiableList;
020
021import com.google.common.annotations.GwtIncompatible;
022import com.google.common.annotations.J2ktIncompatible;
023import com.google.common.annotations.VisibleForTesting;
024import com.google.common.base.MoreObjects;
025import com.google.common.base.Preconditions;
026import com.google.common.base.Supplier;
027import com.google.common.collect.ImmutableList;
028import com.google.common.collect.MapMaker;
029import com.google.common.math.IntMath;
030import com.google.common.primitives.Ints;
031import java.lang.ref.Reference;
032import java.lang.ref.ReferenceQueue;
033import java.lang.ref.WeakReference;
034import java.math.RoundingMode;
035import java.util.List;
036import java.util.concurrent.ConcurrentMap;
037import java.util.concurrent.Semaphore;
038import java.util.concurrent.atomic.AtomicReferenceArray;
039import java.util.concurrent.locks.Condition;
040import java.util.concurrent.locks.Lock;
041import java.util.concurrent.locks.ReadWriteLock;
042import java.util.concurrent.locks.ReentrantLock;
043import java.util.concurrent.locks.ReentrantReadWriteLock;
044import org.jspecify.annotations.Nullable;
045
046/**
047 * A striped {@code Lock/Semaphore/ReadWriteLock}. This offers the underlying lock striping similar
048 * to that of {@code ConcurrentHashMap} in a reusable form, and extends it for semaphores and
049 * read-write locks. Conceptually, lock striping is the technique of dividing a lock into many
050 * <i>stripes</i>, increasing the granularity of a single lock and allowing independent operations
051 * to lock different stripes and proceed concurrently, instead of creating contention for a single
052 * lock.
053 *
054 * <p>The guarantee provided by this class is that equal keys lead to the same lock (or semaphore),
055 * i.e. {@code if (key1.equals(key2))} then {@code striped.get(key1) == striped.get(key2)} (assuming
056 * {@link Object#hashCode()} is correctly implemented for the keys). Note that if {@code key1} is
057 * <strong>not</strong> equal to {@code key2}, it is <strong>not</strong> guaranteed that {@code
058 * striped.get(key1) != striped.get(key2)}; the elements might nevertheless be mapped to the same
059 * lock. The lower the number of stripes, the higher the probability of this happening.
060 *
061 * <p>There are three flavors of this class: {@code Striped<Lock>}, {@code Striped<Semaphore>}, and
062 * {@code Striped<ReadWriteLock>}. For each type, two implementations are offered: {@linkplain
063 * #lock(int) strong} and {@linkplain #lazyWeakLock(int) weak} {@code Striped<Lock>}, {@linkplain
064 * #semaphore(int, int) strong} and {@linkplain #lazyWeakSemaphore(int, int) weak} {@code
065 * Striped<Semaphore>}, and {@linkplain #readWriteLock(int) strong} and {@linkplain
066 * #lazyWeakReadWriteLock(int) weak} {@code Striped<ReadWriteLock>}. <i>Strong</i> means that all
067 * stripes (locks/semaphores) are initialized eagerly, and are not reclaimed unless {@code Striped}
068 * itself is reclaimable. <i>Weak</i> means that locks/semaphores are created lazily, and they are
069 * allowed to be reclaimed if nobody is holding on to them. This is useful, for example, if one
070 * wants to create a {@code Striped<Lock>} of many locks, but worries that in most cases only a
071 * small portion of these would be in use.
072 *
073 * <p>Prior to this class, one might be tempted to use {@code Map<K, Lock>}, where {@code K}
074 * represents the task. This maximizes concurrency by having each unique key mapped to a unique
075 * lock, but also maximizes memory footprint. On the other extreme, one could use a single lock for
076 * all tasks, which minimizes memory footprint but also minimizes concurrency. Instead of choosing
077 * either of these extremes, {@code Striped} allows the user to trade between required concurrency
078 * and memory footprint. For example, if a set of tasks are CPU-bound, one could easily create a
079 * very compact {@code Striped<Lock>} of {@code availableProcessors() * 4} stripes, instead of
080 * possibly thousands of locks which could be created in a {@code Map<K, Lock>} structure.
081 *
082 * @author Dimitris Andreou
083 * @since 13.0
084 */
085@J2ktIncompatible
086@GwtIncompatible
087public abstract class Striped<L> {
088  /**
089   * If there are at least this many stripes, we assume the memory usage of a ConcurrentMap will be
090   * smaller than a large array. (This assumes that in the lazy case, most stripes are unused. As
091   * always, if many stripes are in use, a non-lazy striped makes more sense.)
092   */
093  private static final int LARGE_LAZY_CUTOFF = 1024;
094
095  private Striped() {}
096
097  /**
098   * Returns the stripe that corresponds to the passed key. It is always guaranteed that if {@code
099   * key1.equals(key2)}, then {@code get(key1) == get(key2)}.
100   *
101   * @param key an arbitrary, non-null key
102   * @return the stripe that the passed key corresponds to
103   */
104  public abstract L get(Object key);
105
106  /**
107   * Returns the stripe at the specified index. Valid indexes are 0, inclusively, to {@code size()},
108   * exclusively.
109   *
110   * @param index the index of the stripe to return; must be in {@code [0...size())}
111   * @return the stripe at the specified index
112   */
113  public abstract L getAt(int index);
114
115  /**
116   * Returns the index to which the given key is mapped, so that getAt(indexFor(key)) == get(key).
117   */
118  abstract int indexFor(Object key);
119
120  /** Returns the total number of stripes in this instance. */
121  public abstract int size();
122
123  /**
124   * Returns the stripes that correspond to the passed objects, in ascending (as per {@link
125   * #getAt(int)}) order. Thus, threads that use the stripes in the order returned by this method
126   * are guaranteed to not deadlock each other.
127   *
128   * <p>It should be noted that using a {@code Striped<L>} with relatively few stripes, and {@code
129   * bulkGet(keys)} with a relative large number of keys can cause an excessive number of shared
130   * stripes (much like the birthday paradox, where much fewer than anticipated birthdays are needed
131   * for a pair of them to match). Please consider carefully the implications of the number of
132   * stripes, the intended concurrency level, and the typical number of keys used in a {@code
133   * bulkGet(keys)} operation. See <a href="http://www.mathpages.com/home/kmath199.htm">Balls in
134   * Bins model</a> for mathematical formulas that can be used to estimate the probability of
135   * collisions.
136   *
137   * @param keys arbitrary non-null keys
138   * @return the stripes corresponding to the objects (one per each object, derived by delegating to
139   *     {@link #get(Object)}; may contain duplicates), in an increasing index order.
140   */
141  public Iterable<L> bulkGet(Iterable<? extends Object> keys) {
142    // Initially using the list to store the keys, then reusing it to store the respective L's
143    List<Object> result = newArrayList(keys);
144    if (result.isEmpty()) {
145      return ImmutableList.of();
146    }
147    int[] stripes = new int[result.size()];
148    for (int i = 0; i < result.size(); i++) {
149      stripes[i] = indexFor(result.get(i));
150    }
151    sort(stripes);
152    // optimize for runs of identical stripes
153    int previousStripe = stripes[0];
154    result.set(0, getAt(previousStripe));
155    for (int i = 1; i < result.size(); i++) {
156      int currentStripe = stripes[i];
157      if (currentStripe == previousStripe) {
158        result.set(i, result.get(i - 1));
159      } else {
160        result.set(i, getAt(currentStripe));
161        previousStripe = currentStripe;
162      }
163    }
164    /*
165     * Note that the returned Iterable holds references to the returned stripes, to avoid
166     * error-prone code like:
167     *
168     * Striped<Lock> stripedLock = Striped.lazyWeakXXX(...)'
169     * Iterable<Lock> locks = stripedLock.bulkGet(keys);
170     * for (Lock lock : locks) {
171     *   lock.lock();
172     * }
173     * operation();
174     * for (Lock lock : locks) {
175     *   lock.unlock();
176     * }
177     *
178     * If we only held the int[] stripes, translating it on the fly to L's, the original locks might
179     * be garbage collected after locking them, ending up in a huge mess.
180     */
181    @SuppressWarnings("unchecked") // we carefully replaced all keys with their respective L's
182    List<L> asStripes = (List<L>) result;
183    return unmodifiableList(asStripes);
184  }
185
186  // Static factories
187
188  /**
189   * Creates a {@code Striped<L>} with eagerly initialized, strongly referenced locks. Every lock is
190   * obtained from the passed supplier.
191   *
192   * @param stripes the minimum number of stripes (locks) required
193   * @param supplier a {@code Supplier<L>} object to obtain locks from
194   * @return a new {@code Striped<L>}
195   * @since 33.5.0
196   */
197  public static <L> Striped<L> custom(int stripes, Supplier<L> supplier) {
198    return new CompactStriped<>(stripes, supplier);
199  }
200
201  /**
202   * Creates a {@code Striped<Lock>} with eagerly initialized, strongly referenced locks. Every lock
203   * is reentrant.
204   *
205   * @param stripes the minimum number of stripes (locks) required
206   * @return a new {@code Striped<Lock>}
207   */
208  public static Striped<Lock> lock(int stripes) {
209    return custom(stripes, PaddedLock::new);
210  }
211
212  /**
213   * Creates a {@code Striped<Lock>} with lazily initialized, weakly referenced locks. Every lock is
214   * reentrant.
215   *
216   * @param stripes the minimum number of stripes (locks) required
217   * @return a new {@code Striped<Lock>}
218   */
219  public static Striped<Lock> lazyWeakLock(int stripes) {
220    return lazyWeakCustom(stripes, () -> new ReentrantLock(false));
221  }
222
223  /**
224   * Creates a {@code Striped<L>} with lazily initialized, weakly referenced locks. Every lock is
225   * obtained from the passed supplier.
226   *
227   * @param stripes the minimum number of stripes (locks) required
228   * @param supplier a {@code Supplier<L>} object to obtain locks from
229   * @return a new {@code Striped<L>}
230   */
231  static <L> Striped<L> lazyWeakCustom(int stripes, Supplier<L> supplier) {
232    return stripes < LARGE_LAZY_CUTOFF
233        ? new SmallLazyStriped<L>(stripes, supplier)
234        : new LargeLazyStriped<L>(stripes, supplier);
235  }
236
237  /**
238   * Creates a {@code Striped<Semaphore>} with eagerly initialized, strongly referenced semaphores,
239   * with the specified number of permits.
240   *
241   * @param stripes the minimum number of stripes (semaphores) required
242   * @param permits the number of permits in each semaphore
243   * @return a new {@code Striped<Semaphore>}
244   */
245  public static Striped<Semaphore> semaphore(int stripes, int permits) {
246    return custom(stripes, () -> new PaddedSemaphore(permits));
247  }
248
249  /**
250   * Creates a {@code Striped<Semaphore>} with lazily initialized, weakly referenced semaphores,
251   * with the specified number of permits.
252   *
253   * @param stripes the minimum number of stripes (semaphores) required
254   * @param permits the number of permits in each semaphore
255   * @return a new {@code Striped<Semaphore>}
256   */
257  public static Striped<Semaphore> lazyWeakSemaphore(int stripes, int permits) {
258    return lazyWeakCustom(stripes, () -> new Semaphore(permits, false));
259  }
260
261  /**
262   * Creates a {@code Striped<ReadWriteLock>} with eagerly initialized, strongly referenced
263   * read-write locks. Every lock is reentrant.
264   *
265   * @param stripes the minimum number of stripes (locks) required
266   * @return a new {@code Striped<ReadWriteLock>}
267   */
268  public static Striped<ReadWriteLock> readWriteLock(int stripes) {
269    return custom(stripes, ReentrantReadWriteLock::new);
270  }
271
272  /**
273   * Creates a {@code Striped<ReadWriteLock>} with lazily initialized, weakly referenced read-write
274   * locks. Every lock is reentrant.
275   *
276   * @param stripes the minimum number of stripes (locks) required
277   * @return a new {@code Striped<ReadWriteLock>}
278   */
279  public static Striped<ReadWriteLock> lazyWeakReadWriteLock(int stripes) {
280    return lazyWeakCustom(stripes, WeakSafeReadWriteLock::new);
281  }
282
283  /**
284   * ReadWriteLock implementation whose read and write locks retain a reference back to this lock.
285   * Otherwise, a reference to just the read lock or just the write lock would not suffice to ensure
286   * the {@code ReadWriteLock} is retained.
287   */
288  private static final class WeakSafeReadWriteLock implements ReadWriteLock {
289    private final ReadWriteLock delegate;
290
291    WeakSafeReadWriteLock() {
292      this.delegate = new ReentrantReadWriteLock();
293    }
294
295    @Override
296    public Lock readLock() {
297      return new WeakSafeLock(delegate.readLock(), this);
298    }
299
300    @Override
301    public Lock writeLock() {
302      return new WeakSafeLock(delegate.writeLock(), this);
303    }
304  }
305
306  /** Lock object that ensures a strong reference is retained to a specified object. */
307  private static final class WeakSafeLock extends ForwardingLock {
308    private final Lock delegate;
309
310    @SuppressWarnings("unused")
311    private final WeakSafeReadWriteLock strongReference;
312
313    WeakSafeLock(Lock delegate, WeakSafeReadWriteLock strongReference) {
314      this.delegate = delegate;
315      this.strongReference = strongReference;
316    }
317
318    @Override
319    Lock delegate() {
320      return delegate;
321    }
322
323    @Override
324    public Condition newCondition() {
325      return new WeakSafeCondition(delegate.newCondition(), strongReference);
326    }
327  }
328
329  /** Condition object that ensures a strong reference is retained to a specified object. */
330  private static final class WeakSafeCondition extends ForwardingCondition {
331    private final Condition delegate;
332
333    @SuppressWarnings("unused")
334    private final WeakSafeReadWriteLock strongReference;
335
336    WeakSafeCondition(Condition delegate, WeakSafeReadWriteLock strongReference) {
337      this.delegate = delegate;
338      this.strongReference = strongReference;
339    }
340
341    @Override
342    Condition delegate() {
343      return delegate;
344    }
345  }
346
347  private abstract static class PowerOfTwoStriped<L> extends Striped<L> {
348    /** Capacity (power of two) minus one, for fast mod evaluation */
349    final int mask;
350
351    PowerOfTwoStriped(int stripes) {
352      Preconditions.checkArgument(stripes > 0, "Stripes must be positive");
353      this.mask = stripes > Ints.MAX_POWER_OF_TWO ? ALL_SET : ceilToPowerOfTwo(stripes) - 1;
354    }
355
356    @Override
357    final int indexFor(Object key) {
358      int hash = smear(key.hashCode());
359      return hash & mask;
360    }
361
362    @Override
363    public final L get(Object key) {
364      return getAt(indexFor(key));
365    }
366  }
367
368  /**
369   * Implementation of Striped where 2^k stripes are represented as an array of the same length,
370   * eagerly initialized.
371   */
372  private static final class CompactStriped<L> extends PowerOfTwoStriped<L> {
373    /** Size is a power of two. */
374    private final Object[] array;
375
376    private CompactStriped(int stripes, Supplier<L> supplier) {
377      super(stripes);
378      Preconditions.checkArgument(stripes <= Ints.MAX_POWER_OF_TWO, "Stripes must be <= 2^30)");
379
380      this.array = new Object[mask + 1];
381      for (int i = 0; i < array.length; i++) {
382        array[i] = supplier.get();
383      }
384    }
385
386    @SuppressWarnings("unchecked") // we only put L's in the array
387    @Override
388    public L getAt(int index) {
389      return (L) array[index];
390    }
391
392    @Override
393    public int size() {
394      return array.length;
395    }
396  }
397
398  /**
399   * Implementation of Striped where up to 2^k stripes can be represented, using an
400   * AtomicReferenceArray of size 2^k. To map a user key into a stripe, we take a k-bit slice of the
401   * user key's (smeared) hashCode(). The stripes are lazily initialized and are weakly referenced.
402   */
403  @VisibleForTesting
404  static final class SmallLazyStriped<L> extends PowerOfTwoStriped<L> {
405    final AtomicReferenceArray<@Nullable ArrayReference<? extends L>> locks;
406    final Supplier<L> supplier;
407    final int size;
408    final ReferenceQueue<L> queue = new ReferenceQueue<>();
409
410    SmallLazyStriped(int stripes, Supplier<L> supplier) {
411      super(stripes);
412      this.size = (mask == ALL_SET) ? Integer.MAX_VALUE : mask + 1;
413      this.locks = new AtomicReferenceArray<>(size);
414      this.supplier = supplier;
415    }
416
417    @Override
418    public L getAt(int index) {
419      if (size != Integer.MAX_VALUE) {
420        Preconditions.checkElementIndex(index, size());
421      } // else no check necessary, all index values are valid
422      ArrayReference<? extends L> existingRef = locks.get(index);
423      L existing = existingRef == null ? null : existingRef.get();
424      if (existing != null) {
425        return existing;
426      }
427      L created = supplier.get();
428      ArrayReference<L> newRef = new ArrayReference<>(created, index, queue);
429      while (!locks.compareAndSet(index, existingRef, newRef)) {
430        // we raced, we need to re-read and try again
431        existingRef = locks.get(index);
432        existing = existingRef == null ? null : existingRef.get();
433        if (existing != null) {
434          return existing;
435        }
436      }
437      drainQueue();
438      return created;
439    }
440
441    // N.B. Draining the queue is only necessary to ensure that we don't accumulate empty references
442    // in the array. We could skip this if we decide we don't care about holding on to Reference
443    // objects indefinitely.
444    private void drainQueue() {
445      Reference<? extends L> ref;
446      while ((ref = queue.poll()) != null) {
447        // We only ever register ArrayReferences with the queue so this is always safe.
448        ArrayReference<? extends L> arrayRef = (ArrayReference<? extends L>) ref;
449        // Try to clear out the array slot, n.b. if we fail that is fine, in either case the
450        // arrayRef will be out of the array after this step.
451        locks.compareAndSet(arrayRef.index, arrayRef, null);
452      }
453    }
454
455    @Override
456    public int size() {
457      return size;
458    }
459
460    private static final class ArrayReference<L> extends WeakReference<L> {
461      final int index;
462
463      ArrayReference(L referent, int index, ReferenceQueue<L> queue) {
464        super(referent, queue);
465        this.index = index;
466      }
467    }
468  }
469
470  /**
471   * Implementation of Striped where up to 2^k stripes can be represented, using a ConcurrentMap
472   * where the key domain is [0..2^k). To map a user key into a stripe, we take a k-bit slice of the
473   * user key's (smeared) hashCode(). The stripes are lazily initialized and are weakly referenced.
474   */
475  @VisibleForTesting
476  static final class LargeLazyStriped<L> extends PowerOfTwoStriped<L> {
477    final ConcurrentMap<Integer, L> locks;
478    final Supplier<L> supplier;
479    final int size;
480
481    LargeLazyStriped(int stripes, Supplier<L> supplier) {
482      super(stripes);
483      this.size = (mask == ALL_SET) ? Integer.MAX_VALUE : mask + 1;
484      this.supplier = supplier;
485      this.locks = new MapMaker().weakValues().makeMap();
486    }
487
488    @Override
489    public L getAt(int index) {
490      if (size != Integer.MAX_VALUE) {
491        Preconditions.checkElementIndex(index, size());
492      } // else no check necessary, all index values are valid
493      L existing = locks.get(index);
494      if (existing != null) {
495        return existing;
496      }
497      L created = supplier.get();
498      existing = locks.putIfAbsent(index, created);
499      return MoreObjects.firstNonNull(existing, created);
500    }
501
502    @Override
503    public int size() {
504      return size;
505    }
506  }
507
508  /** A bit mask were all bits are set. */
509  private static final int ALL_SET = ~0;
510
511  private static int ceilToPowerOfTwo(int x) {
512    return 1 << IntMath.log2(x, RoundingMode.CEILING);
513  }
514
515  /*
516   * This method was written by Doug Lea with assistance from members of JCP JSR-166 Expert Group
517   * and released to the public domain, as explained at
518   * http://creativecommons.org/licenses/publicdomain
519   *
520   * As of 2010/06/11, this method is identical to the (package private) hash method in OpenJDK 7's
521   * java.util.HashMap class.
522   */
523  // Copied from java/com/google/common/collect/Hashing.java
524  private static int smear(int hashCode) {
525    hashCode ^= (hashCode >>> 20) ^ (hashCode >>> 12);
526    return hashCode ^ (hashCode >>> 7) ^ (hashCode >>> 4);
527  }
528
529  private static final class PaddedLock extends ReentrantLock {
530    /*
531     * Padding from 40 into 64 bytes, same size as cache line. Might be beneficial to add a fourth
532     * long here, to minimize chance of interference between consecutive locks, but I couldn't
533     * observe any benefit from that.
534     */
535    long unused1;
536    long unused2;
537    long unused3;
538
539    PaddedLock() {
540      super(false);
541    }
542  }
543
544  private static final class PaddedSemaphore extends Semaphore {
545    // See PaddedReentrantLock comment
546    long unused1;
547    long unused2;
548    long unused3;
549
550    PaddedSemaphore(int permits) {
551      super(permits, false);
552    }
553  }
554}