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