StripeIndex.java

  1. /*
  2.  * #%L
  3.  * wcm.io
  4.  * %%
  5.  * Copyright (C) 2023 wcm.io
  6.  * %%
  7.  * Licensed under the Apache License, Version 2.0 (the "License");
  8.  * you may not use this file except in compliance with the License.
  9.  * You may obtain a copy of the License at
  10.  *
  11.  *      http://www.apache.org/licenses/LICENSE-2.0
  12.  *
  13.  * Unless required by applicable law or agreed to in writing, software
  14.  * distributed under the License is distributed on an "AS IS" BASIS,
  15.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16.  * See the License for the specific language governing permissions and
  17.  * limitations under the License.
  18.  * #L%
  19.  */
  20. package io.wcm.handler.mediasource.dam.impl.metadata.concurrency;

  21. /**
  22.  * Maps keys to a striped index set. Each key is mapped to a index within the max stripe count.
  23.  *
  24.  * <p>
  25.  * The logic is extracted from <a href=
  26.  * "https://github.com/google/guava/blob/master/guava/src/com/google/common/util/concurrent/Striped.java">Striped</a>,
  27.  * initially written by Dimitris Andreou from the Guava team (Apache 2.0 license).
  28.  * </p>
  29.  */
  30. final class StripeIndex {

  31.   // Capacity (power of two) minus one, for fast mod evaluation
  32.   private final int mask;
  33.   private final int size;

  34.   // A bit mask were all bits are set.
  35.   private static final int ALL_SET = ~0;

  36.   // The largest power of two that can be represented as an {@code int}.
  37.   private static final int MAX_POWER_OF_TWO = 1 << (Integer.SIZE - 2);

  38.   /**
  39.    * @param stripes the minimum number of stripes required
  40.    */
  41.   StripeIndex(int stripes) {
  42.     if (stripes <= 0) {
  43.       throw new IllegalArgumentException("Invalid number of stripes: " + stripes);
  44.     }
  45.     this.mask = stripes > MAX_POWER_OF_TWO ? ALL_SET : ceilToPowerOfTwo(stripes) - 1;
  46.     this.size = (mask == ALL_SET) ? Integer.MAX_VALUE : mask + 1;
  47.   }

  48.   /** Returns the total number of stripes in this instance. */
  49.   int size() {
  50.     return size;
  51.   }

  52.   /**
  53.    * Returns the index to which the given key is mapped, so that getAt(indexFor(key)) == get(key).
  54.    */
  55.   int indexFor(Object key) {
  56.     int hash = smear(key.hashCode());
  57.     return hash & mask;
  58.   }

  59.   private static int smear(int hashCode) {
  60.     int newHashCode = hashCode;
  61.     newHashCode ^= (newHashCode >>> 20) ^ (newHashCode >>> 12);
  62.     return newHashCode ^ (newHashCode >>> 7) ^ (newHashCode >>> 4);
  63.   }

  64.   private static int ceilToPowerOfTwo(int x) {
  65.     return 1 << log2RoundCeiling(x);
  66.   }

  67.   private static int log2RoundCeiling(int x) {
  68.     return Integer.SIZE - Integer.numberOfLeadingZeros(x - 1);
  69.   }

  70. }