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
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    Arrays.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 Collections.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   */
196  static <L> Striped<L> custom(int stripes, Supplier<L> supplier) {
197    return new CompactStriped<>(stripes, supplier);
198  }
199
200  /**
201   * Creates a {@code Striped<Lock>} with eagerly initialized, strongly referenced locks. Every lock
202   * is reentrant.
203   *
204   * @param stripes the minimum number of stripes (locks) required
205   * @return a new {@code Striped<Lock>}
206   */
207  public static Striped<Lock> lock(int stripes) {
208    return custom(stripes, PaddedLock::new);
209  }
210
211  /**
212   * Creates a {@code Striped<Lock>} with lazily initialized, weakly referenced locks. Every lock is
213   * reentrant.
214   *
215   * @param stripes the minimum number of stripes (locks) required
216   * @return a new {@code Striped<Lock>}
217   */
218  public static Striped<Lock> lazyWeakLock(int stripes) {
219    return lazyWeakCustom(stripes, () -> new ReentrantLock(false));
220  }
221
222  /**
223   * Creates a {@code Striped<L>} with lazily initialized, weakly referenced locks. Every lock is
224   * obtained from the passed supplier.
225   *
226   * @param stripes the minimum number of stripes (locks) required
227   * @param supplier a {@code Supplier<L>} object to obtain locks from
228   * @return a new {@code Striped<L>}
229   */
230  static <L> Striped<L> lazyWeakCustom(int stripes, Supplier<L> supplier) {
231    return stripes < LARGE_LAZY_CUTOFF
232        ? new SmallLazyStriped<L>(stripes, supplier)
233        : new LargeLazyStriped<L>(stripes, supplier);
234  }
235
236  /**
237   * Creates a {@code Striped<Semaphore>} with eagerly initialized, strongly referenced semaphores,
238   * with the specified number of permits.
239   *
240   * @param stripes the minimum number of stripes (semaphores) required
241   * @param permits the number of permits in each semaphore
242   * @return a new {@code Striped<Semaphore>}
243   */
244  public static Striped<Semaphore> semaphore(int stripes, int permits) {
245    return custom(stripes, () -> new PaddedSemaphore(permits));
246  }
247
248  /**
249   * Creates a {@code Striped<Semaphore>} with lazily initialized, weakly referenced semaphores,
250   * with the specified number of permits.
251   *
252   * @param stripes the minimum number of stripes (semaphores) required
253   * @param permits the number of permits in each semaphore
254   * @return a new {@code Striped<Semaphore>}
255   */
256  public static Striped<Semaphore> lazyWeakSemaphore(int stripes, int permits) {
257    return lazyWeakCustom(stripes, () -> new Semaphore(permits, false));
258  }
259
260  /**
261   * Creates a {@code Striped<ReadWriteLock>} with eagerly initialized, strongly referenced
262   * read-write locks. Every lock is reentrant.
263   *
264   * @param stripes the minimum number of stripes (locks) required
265   * @return a new {@code Striped<ReadWriteLock>}
266   */
267  public static Striped<ReadWriteLock> readWriteLock(int stripes) {
268    return custom(stripes, ReentrantReadWriteLock::new);
269  }
270
271  /**
272   * Creates a {@code Striped<ReadWriteLock>} with lazily initialized, weakly referenced read-write
273   * locks. Every lock is reentrant.
274   *
275   * @param stripes the minimum number of stripes (locks) required
276   * @return a new {@code Striped<ReadWriteLock>}
277   */
278  public static Striped<ReadWriteLock> lazyWeakReadWriteLock(int stripes) {
279    return lazyWeakCustom(stripes, WeakSafeReadWriteLock::new);
280  }
281  /**
282   * ReadWriteLock implementation whose read and write locks retain a reference back to this lock.
283   * Otherwise, a reference to just the read lock or just the write lock would not suffice to ensure
284   * the {@code ReadWriteLock} is retained.
285   */
286  private static final class WeakSafeReadWriteLock implements ReadWriteLock {
287    private final ReadWriteLock delegate;
288
289    WeakSafeReadWriteLock() {
290      this.delegate = new ReentrantReadWriteLock();
291    }
292
293    @Override
294    public Lock readLock() {
295      return new WeakSafeLock(delegate.readLock(), this);
296    }
297
298    @Override
299    public Lock writeLock() {
300      return new WeakSafeLock(delegate.writeLock(), this);
301    }
302  }
303
304  /** Lock object that ensures a strong reference is retained to a specified object. */
305  private static final class WeakSafeLock extends ForwardingLock {
306    private final Lock delegate;
307
308    @SuppressWarnings("unused")
309    private final WeakSafeReadWriteLock strongReference;
310
311    WeakSafeLock(Lock delegate, WeakSafeReadWriteLock strongReference) {
312      this.delegate = delegate;
313      this.strongReference = strongReference;
314    }
315
316    @Override
317    Lock delegate() {
318      return delegate;
319    }
320
321    @Override
322    public Condition newCondition() {
323      return new WeakSafeCondition(delegate.newCondition(), strongReference);
324    }
325  }
326
327  /** Condition object that ensures a strong reference is retained to a specified object. */
328  private static final class WeakSafeCondition extends ForwardingCondition {
329    private final Condition delegate;
330
331    @SuppressWarnings("unused")
332    private final WeakSafeReadWriteLock strongReference;
333
334    WeakSafeCondition(Condition delegate, WeakSafeReadWriteLock strongReference) {
335      this.delegate = delegate;
336      this.strongReference = strongReference;
337    }
338
339    @Override
340    Condition delegate() {
341      return delegate;
342    }
343  }
344
345  private abstract static class PowerOfTwoStriped<L> extends Striped<L> {
346    /** Capacity (power of two) minus one, for fast mod evaluation */
347    final int mask;
348
349    PowerOfTwoStriped(int stripes) {
350      Preconditions.checkArgument(stripes > 0, "Stripes must be positive");
351      this.mask = stripes > Ints.MAX_POWER_OF_TWO ? ALL_SET : ceilToPowerOfTwo(stripes) - 1;
352    }
353
354    @Override
355    final int indexFor(Object key) {
356      int hash = smear(key.hashCode());
357      return hash & mask;
358    }
359
360    @Override
361    public final L get(Object key) {
362      return getAt(indexFor(key));
363    }
364  }
365
366  /**
367   * Implementation of Striped where 2^k stripes are represented as an array of the same length,
368   * eagerly initialized.
369   */
370  private static class CompactStriped<L> extends PowerOfTwoStriped<L> {
371    /** Size is a power of two. */
372    private final Object[] array;
373
374    private CompactStriped(int stripes, Supplier<L> supplier) {
375      super(stripes);
376      Preconditions.checkArgument(stripes <= Ints.MAX_POWER_OF_TWO, "Stripes must be <= 2^30)");
377
378      this.array = new Object[mask + 1];
379      for (int i = 0; i < array.length; i++) {
380        array[i] = supplier.get();
381      }
382    }
383
384    @SuppressWarnings("unchecked") // we only put L's in the array
385    @Override
386    public L getAt(int index) {
387      return (L) array[index];
388    }
389
390    @Override
391    public int size() {
392      return array.length;
393    }
394  }
395
396  /**
397   * Implementation of Striped where up to 2^k stripes can be represented, using an
398   * AtomicReferenceArray of size 2^k. To map a user key into a stripe, we take a k-bit slice of the
399   * user key's (smeared) hashCode(). The stripes are lazily initialized and are weakly referenced.
400   */
401  @VisibleForTesting
402  static class SmallLazyStriped<L> extends PowerOfTwoStriped<L> {
403    final AtomicReferenceArray<@Nullable ArrayReference<? extends L>> locks;
404    final Supplier<L> supplier;
405    final int size;
406    final ReferenceQueue<L> queue = new ReferenceQueue<>();
407
408    SmallLazyStriped(int stripes, Supplier<L> supplier) {
409      super(stripes);
410      this.size = (mask == ALL_SET) ? Integer.MAX_VALUE : mask + 1;
411      this.locks = new AtomicReferenceArray<>(size);
412      this.supplier = supplier;
413    }
414
415    @Override
416    public L getAt(int index) {
417      if (size != Integer.MAX_VALUE) {
418        Preconditions.checkElementIndex(index, size());
419      } // else no check necessary, all index values are valid
420      ArrayReference<? extends L> existingRef = locks.get(index);
421      L existing = existingRef == null ? null : existingRef.get();
422      if (existing != null) {
423        return existing;
424      }
425      L created = supplier.get();
426      ArrayReference<L> newRef = new ArrayReference<>(created, index, queue);
427      while (!locks.compareAndSet(index, existingRef, newRef)) {
428        // we raced, we need to re-read and try again
429        existingRef = locks.get(index);
430        existing = existingRef == null ? null : existingRef.get();
431        if (existing != null) {
432          return existing;
433        }
434      }
435      drainQueue();
436      return created;
437    }
438
439    // N.B. Draining the queue is only necessary to ensure that we don't accumulate empty references
440    // in the array. We could skip this if we decide we don't care about holding on to Reference
441    // objects indefinitely.
442    private void drainQueue() {
443      Reference<? extends L> ref;
444      while ((ref = queue.poll()) != null) {
445        // We only ever register ArrayReferences with the queue so this is always safe.
446        ArrayReference<? extends L> arrayRef = (ArrayReference<? extends L>) ref;
447        // Try to clear out the array slot, n.b. if we fail that is fine, in either case the
448        // arrayRef will be out of the array after this step.
449        locks.compareAndSet(arrayRef.index, arrayRef, null);
450      }
451    }
452
453    @Override
454    public int size() {
455      return size;
456    }
457
458    private static final class ArrayReference<L> extends WeakReference<L> {
459      final int index;
460
461      ArrayReference(L referent, int index, ReferenceQueue<L> queue) {
462        super(referent, queue);
463        this.index = index;
464      }
465    }
466  }
467
468  /**
469   * Implementation of Striped where up to 2^k stripes can be represented, using a ConcurrentMap
470   * where the key domain is [0..2^k). To map a user key into a stripe, we take a k-bit slice of the
471   * user key's (smeared) hashCode(). The stripes are lazily initialized and are weakly referenced.
472   */
473  @VisibleForTesting
474  static class LargeLazyStriped<L> extends PowerOfTwoStriped<L> {
475    final ConcurrentMap<Integer, L> locks;
476    final Supplier<L> supplier;
477    final int size;
478
479    LargeLazyStriped(int stripes, Supplier<L> supplier) {
480      super(stripes);
481      this.size = (mask == ALL_SET) ? Integer.MAX_VALUE : mask + 1;
482      this.supplier = supplier;
483      this.locks = new MapMaker().weakValues().makeMap();
484    }
485
486    @Override
487    public L getAt(int index) {
488      if (size != Integer.MAX_VALUE) {
489        Preconditions.checkElementIndex(index, size());
490      } // else no check necessary, all index values are valid
491      L existing = locks.get(index);
492      if (existing != null) {
493        return existing;
494      }
495      L created = supplier.get();
496      existing = locks.putIfAbsent(index, created);
497      return MoreObjects.firstNonNull(existing, created);
498    }
499
500    @Override
501    public int size() {
502      return size;
503    }
504  }
505
506  /** A bit mask were all bits are set. */
507  private static final int ALL_SET = ~0;
508
509  private static int ceilToPowerOfTwo(int x) {
510    return 1 << IntMath.log2(x, RoundingMode.CEILING);
511  }
512
513  /*
514   * This method was written by Doug Lea with assistance from members of JCP JSR-166 Expert Group
515   * and released to the public domain, as explained at
516   * http://creativecommons.org/licenses/publicdomain
517   *
518   * As of 2010/06/11, this method is identical to the (package private) hash method in OpenJDK 7's
519   * java.util.HashMap class.
520   */
521  // Copied from java/com/google/common/collect/Hashing.java
522  private static int smear(int hashCode) {
523    hashCode ^= (hashCode >>> 20) ^ (hashCode >>> 12);
524    return hashCode ^ (hashCode >>> 7) ^ (hashCode >>> 4);
525  }
526
527  private static class PaddedLock extends ReentrantLock {
528    /*
529     * Padding from 40 into 64 bytes, same size as cache line. Might be beneficial to add a fourth
530     * long here, to minimize chance of interference between consecutive locks, but I couldn't
531     * observe any benefit from that.
532     */
533    long unused1;
534    long unused2;
535    long unused3;
536
537    PaddedLock() {
538      super(false);
539    }
540  }
541
542  private static class PaddedSemaphore extends Semaphore {
543    // See PaddedReentrantLock comment
544    long unused1;
545    long unused2;
546    long unused3;
547
548    PaddedSemaphore(int permits) {
549      super(permits, false);
550    }
551  }
552}