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