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;
018
019import com.google.common.annotations.GwtIncompatible;
020import com.google.common.annotations.J2ktIncompatible;
021import com.google.common.annotations.VisibleForTesting;
022import com.google.common.base.MoreObjects;
023import com.google.common.base.Preconditions;
024import com.google.common.base.Supplier;
025import com.google.common.collect.ImmutableList;
026import com.google.common.collect.MapMaker;
027import com.google.common.math.IntMath;
028import com.google.common.primitives.Ints;
029import java.lang.ref.Reference;
030import java.lang.ref.ReferenceQueue;
031import java.lang.ref.WeakReference;
032import java.math.RoundingMode;
033import java.util.Arrays;
034import java.util.Collections;
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.checkerframework.checker.nullness.qual.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
087@ElementTypesAreNonnullByDefault
088public abstract class Striped<L> {
089  /**
090   * If there are at least this many stripes, we assume the memory usage of a ConcurrentMap will be
091   * smaller than a large array. (This assumes that in the lazy case, most stripes are unused. As
092   * always, if many stripes are in use, a non-lazy striped makes more sense.)
093   */
094  private static final int LARGE_LAZY_CUTOFF = 1024;
095
096  private Striped() {}
097
098  /**
099   * Returns the stripe that corresponds to the passed key. It is always guaranteed that if {@code
100   * key1.equals(key2)}, then {@code get(key1) == get(key2)}.
101   *
102   * @param key an arbitrary, non-null key
103   * @return the stripe that the passed key corresponds to
104   */
105  public abstract L get(Object key);
106
107  /**
108   * Returns the stripe at the specified index. Valid indexes are 0, inclusively, to {@code size()},
109   * exclusively.
110   *
111   * @param index the index of the stripe to return; must be in {@code [0...size())}
112   * @return the stripe at the specified index
113   */
114  public abstract L getAt(int index);
115
116  /**
117   * Returns the index to which the given key is mapped, so that getAt(indexFor(key)) == get(key).
118   */
119  abstract int indexFor(Object key);
120
121  /** Returns the total number of stripes in this instance. */
122  public abstract int size();
123
124  /**
125   * Returns the stripes that correspond to the passed objects, in ascending (as per {@link
126   * #getAt(int)}) order. Thus, threads that use the stripes in the order returned by this method
127   * are guaranteed to not deadlock each other.
128   *
129   * <p>It should be noted that using a {@code Striped<L>} with relatively few stripes, and {@code
130   * bulkGet(keys)} with a relative large number of keys can cause an excessive number of shared
131   * stripes (much like the birthday paradox, where much fewer than anticipated birthdays are needed
132   * for a pair of them to match). Please consider carefully the implications of the number of
133   * stripes, the intended concurrency level, and the typical number of keys used in a {@code
134   * bulkGet(keys)} operation. See <a href="http://www.mathpages.com/home/kmath199.htm">Balls in
135   * Bins model</a> for mathematical formulas that can be used to estimate the probability of
136   * collisions.
137   *
138   * @param keys arbitrary non-null keys
139   * @return the stripes corresponding to the objects (one per each object, derived by delegating to
140   *     {@link #get(Object)}; may contain duplicates), in an increasing index order.
141   */
142  public Iterable<L> bulkGet(Iterable<? extends Object> keys) {
143    // Initially using the list to store the keys, then reusing it to store the respective L's
144    List<Object> result = newArrayList(keys);
145    if (result.isEmpty()) {
146      return ImmutableList.of();
147    }
148    int[] stripes = new int[result.size()];
149    for (int i = 0; i < result.size(); i++) {
150      stripes[i] = indexFor(result.get(i));
151    }
152    Arrays.sort(stripes);
153    // optimize for runs of identical stripes
154    int previousStripe = stripes[0];
155    result.set(0, getAt(previousStripe));
156    for (int i = 1; i < result.size(); i++) {
157      int currentStripe = stripes[i];
158      if (currentStripe == previousStripe) {
159        result.set(i, result.get(i - 1));
160      } else {
161        result.set(i, getAt(currentStripe));
162        previousStripe = currentStripe;
163      }
164    }
165    /*
166     * Note that the returned Iterable holds references to the returned stripes, to avoid
167     * error-prone code like:
168     *
169     * Striped<Lock> stripedLock = Striped.lazyWeakXXX(...)'
170     * Iterable<Lock> locks = stripedLock.bulkGet(keys);
171     * for (Lock lock : locks) {
172     *   lock.lock();
173     * }
174     * operation();
175     * for (Lock lock : locks) {
176     *   lock.unlock();
177     * }
178     *
179     * If we only held the int[] stripes, translating it on the fly to L's, the original locks might
180     * be garbage collected after locking them, ending up in a huge mess.
181     */
182    @SuppressWarnings("unchecked") // we carefully replaced all keys with their respective L's
183    List<L> asStripes = (List<L>) result;
184    return Collections.unmodifiableList(asStripes);
185  }
186
187  // Static factories
188
189  /**
190   * Creates a {@code Striped<L>} with eagerly initialized, strongly referenced locks. Every lock is
191   * obtained from the passed supplier.
192   *
193   * @param stripes the minimum number of stripes (locks) required
194   * @param supplier a {@code Supplier<L>} object to obtain locks from
195   * @return a new {@code Striped<L>}
196   */
197  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   * ReadWriteLock implementation whose read and write locks retain a reference back to this lock.
284   * Otherwise, a reference to just the read lock or just the write lock would not suffice to ensure
285   * the {@code ReadWriteLock} is retained.
286   */
287  private static final class WeakSafeReadWriteLock implements ReadWriteLock {
288    private final ReadWriteLock delegate;
289
290    WeakSafeReadWriteLock() {
291      this.delegate = new ReentrantReadWriteLock();
292    }
293
294    @Override
295    public Lock readLock() {
296      return new WeakSafeLock(delegate.readLock(), this);
297    }
298
299    @Override
300    public Lock writeLock() {
301      return new WeakSafeLock(delegate.writeLock(), this);
302    }
303  }
304
305  /** Lock object that ensures a strong reference is retained to a specified object. */
306  private static final class WeakSafeLock extends ForwardingLock {
307    private final Lock delegate;
308
309    @SuppressWarnings("unused")
310    private final WeakSafeReadWriteLock strongReference;
311
312    WeakSafeLock(Lock delegate, WeakSafeReadWriteLock strongReference) {
313      this.delegate = delegate;
314      this.strongReference = strongReference;
315    }
316
317    @Override
318    Lock delegate() {
319      return delegate;
320    }
321
322    @Override
323    public Condition newCondition() {
324      return new WeakSafeCondition(delegate.newCondition(), strongReference);
325    }
326  }
327
328  /** Condition object that ensures a strong reference is retained to a specified object. */
329  private static final class WeakSafeCondition extends ForwardingCondition {
330    private final Condition delegate;
331
332    @SuppressWarnings("unused")
333    private final WeakSafeReadWriteLock strongReference;
334
335    WeakSafeCondition(Condition delegate, WeakSafeReadWriteLock strongReference) {
336      this.delegate = delegate;
337      this.strongReference = strongReference;
338    }
339
340    @Override
341    Condition delegate() {
342      return delegate;
343    }
344  }
345
346  private abstract static class PowerOfTwoStriped<L> extends Striped<L> {
347    /** Capacity (power of two) minus one, for fast mod evaluation */
348    final int mask;
349
350    PowerOfTwoStriped(int stripes) {
351      Preconditions.checkArgument(stripes > 0, "Stripes must be positive");
352      this.mask = stripes > Ints.MAX_POWER_OF_TWO ? ALL_SET : ceilToPowerOfTwo(stripes) - 1;
353    }
354
355    @Override
356    final int indexFor(Object key) {
357      int hash = smear(key.hashCode());
358      return hash & mask;
359    }
360
361    @Override
362    public final L get(Object key) {
363      return getAt(indexFor(key));
364    }
365  }
366
367  /**
368   * Implementation of Striped where 2^k stripes are represented as an array of the same length,
369   * eagerly initialized.
370   */
371  private static class CompactStriped<L> extends PowerOfTwoStriped<L> {
372    /** Size is a power of two. */
373    private final Object[] array;
374
375    private CompactStriped(int stripes, Supplier<L> supplier) {
376      super(stripes);
377      Preconditions.checkArgument(stripes <= Ints.MAX_POWER_OF_TWO, "Stripes must be <= 2^30)");
378
379      this.array = new Object[mask + 1];
380      for (int i = 0; i < array.length; i++) {
381        array[i] = supplier.get();
382      }
383    }
384
385    @SuppressWarnings("unchecked") // we only put L's in the array
386    @Override
387    public L getAt(int index) {
388      return (L) array[index];
389    }
390
391    @Override
392    public int size() {
393      return array.length;
394    }
395  }
396
397  /**
398   * Implementation of Striped where up to 2^k stripes can be represented, using an
399   * AtomicReferenceArray of size 2^k. To map a user key into a stripe, we take a k-bit slice of the
400   * user key's (smeared) hashCode(). The stripes are lazily initialized and are weakly referenced.
401   */
402  @VisibleForTesting
403  static class SmallLazyStriped<L> extends PowerOfTwoStriped<L> {
404    final AtomicReferenceArray<@Nullable ArrayReference<? extends L>> locks;
405    final Supplier<L> supplier;
406    final int size;
407    final ReferenceQueue<L> queue = new ReferenceQueue<>();
408
409    SmallLazyStriped(int stripes, Supplier<L> supplier) {
410      super(stripes);
411      this.size = (mask == ALL_SET) ? Integer.MAX_VALUE : mask + 1;
412      this.locks = new AtomicReferenceArray<>(size);
413      this.supplier = supplier;
414    }
415
416    @Override
417    public L getAt(int index) {
418      if (size != Integer.MAX_VALUE) {
419        Preconditions.checkElementIndex(index, size());
420      } // else no check necessary, all index values are valid
421      ArrayReference<? extends L> existingRef = locks.get(index);
422      L existing = existingRef == null ? null : existingRef.get();
423      if (existing != null) {
424        return existing;
425      }
426      L created = supplier.get();
427      ArrayReference<L> newRef = new ArrayReference<>(created, index, queue);
428      while (!locks.compareAndSet(index, existingRef, newRef)) {
429        // we raced, we need to re-read and try again
430        existingRef = locks.get(index);
431        existing = existingRef == null ? null : existingRef.get();
432        if (existing != null) {
433          return existing;
434        }
435      }
436      drainQueue();
437      return created;
438    }
439
440    // N.B. Draining the queue is only necessary to ensure that we don't accumulate empty references
441    // in the array. We could skip this if we decide we don't care about holding on to Reference
442    // objects indefinitely.
443    private void drainQueue() {
444      Reference<? extends L> ref;
445      while ((ref = queue.poll()) != null) {
446        // We only ever register ArrayReferences with the queue so this is always safe.
447        ArrayReference<? extends L> arrayRef = (ArrayReference<? extends L>) ref;
448        // Try to clear out the array slot, n.b. if we fail that is fine, in either case the
449        // arrayRef will be out of the array after this step.
450        locks.compareAndSet(arrayRef.index, arrayRef, null);
451      }
452    }
453
454    @Override
455    public int size() {
456      return size;
457    }
458
459    private static final class ArrayReference<L> extends WeakReference<L> {
460      final int index;
461
462      ArrayReference(L referent, int index, ReferenceQueue<L> queue) {
463        super(referent, queue);
464        this.index = index;
465      }
466    }
467  }
468
469  /**
470   * Implementation of Striped where up to 2^k stripes can be represented, using a ConcurrentMap
471   * where the key domain is [0..2^k). To map a user key into a stripe, we take a k-bit slice of the
472   * user key's (smeared) hashCode(). The stripes are lazily initialized and are weakly referenced.
473   */
474  @VisibleForTesting
475  static class LargeLazyStriped<L> extends PowerOfTwoStriped<L> {
476    final ConcurrentMap<Integer, L> locks;
477    final Supplier<L> supplier;
478    final int size;
479
480    LargeLazyStriped(int stripes, Supplier<L> supplier) {
481      super(stripes);
482      this.size = (mask == ALL_SET) ? Integer.MAX_VALUE : mask + 1;
483      this.supplier = supplier;
484      this.locks = new MapMaker().weakValues().makeMap();
485    }
486
487    @Override
488    public L getAt(int index) {
489      if (size != Integer.MAX_VALUE) {
490        Preconditions.checkElementIndex(index, size());
491      } // else no check necessary, all index values are valid
492      L existing = locks.get(index);
493      if (existing != null) {
494        return existing;
495      }
496      L created = supplier.get();
497      existing = locks.putIfAbsent(index, created);
498      return MoreObjects.firstNonNull(existing, created);
499    }
500
501    @Override
502    public int size() {
503      return size;
504    }
505  }
506
507  /** A bit mask were all bits are set. */
508  private static final int ALL_SET = ~0;
509
510  private static int ceilToPowerOfTwo(int x) {
511    return 1 << IntMath.log2(x, RoundingMode.CEILING);
512  }
513
514  /*
515   * This method was written by Doug Lea with assistance from members of JCP JSR-166 Expert Group
516   * and released to the public domain, as explained at
517   * http://creativecommons.org/licenses/publicdomain
518   *
519   * As of 2010/06/11, this method is identical to the (package private) hash method in OpenJDK 7's
520   * java.util.HashMap class.
521   */
522  // Copied from java/com/google/common/collect/Hashing.java
523  private static int smear(int hashCode) {
524    hashCode ^= (hashCode >>> 20) ^ (hashCode >>> 12);
525    return hashCode ^ (hashCode >>> 7) ^ (hashCode >>> 4);
526  }
527
528  private static class PaddedLock extends ReentrantLock {
529    /*
530     * Padding from 40 into 64 bytes, same size as cache line. Might be beneficial to add a fourth
531     * long here, to minimize chance of interference between consecutive locks, but I couldn't
532     * observe any benefit from that.
533     */
534    long unused1;
535    long unused2;
536    long unused3;
537
538    PaddedLock() {
539      super(false);
540    }
541  }
542
543  private static class PaddedSemaphore extends Semaphore {
544    // See PaddedReentrantLock comment
545    long unused1;
546    long unused2;
547    long unused3;
548
549    PaddedSemaphore(int permits) {
550      super(permits, false);
551    }
552  }
553}