/*
 * Copyright 2016 Ben Manes. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.github.benmanes.caffeine.cache;

import java.lang.reflect.Field;

import com.github.benmanes.caffeine.base.UnsafeAccess;
import com.google.common.base.Throwables;

/**
 * A hook to enforce a predictable random seed is used by Caffeine's caches.
 *
 * @author ben.manes@gmail.com (Ben Manes)
 */
public final class RandomSeedEnforcer {
  static final long PROBE = UnsafeAccess.objectFieldOffset(Thread.class, "threadLocalRandomProbe");
  static final long SEED = UnsafeAccess.objectFieldOffset(Thread.class, "threadLocalRandomSeed");
  static final int RANDOM_SEED = 1033096058;

  private RandomSeedEnforcer() {}

  /** Force the random seed to a predictable value. */
  public static void ensureRandomSeed(Cache<?, ?> cache) {
    if (!(cache.asMap() instanceof BoundedLocalCache<?, ?>)) {
      return;
    }

    BoundedLocalCache<?, ?> map = (BoundedLocalCache<?, ?>) cache.asMap();
    resetThreadLocalRandom();
    if (map.evicts()) {
      ensureRandomSeed(map.frequencySketch());
    }
  }

  /** Forces the eviction jitter to be predictable. */
  private static void resetThreadLocalRandom() {
    UnsafeAccess.UNSAFE.putInt(Thread.currentThread(), PROBE, 0x9e3779b9);
    UnsafeAccess.UNSAFE.putLong(Thread.currentThread(), SEED, RANDOM_SEED);
  }

  /** Force the random seed to a predictable value. */
  public static void ensureRandomSeed(FrequencySketch<?> sketch) {
    try {
      Field field = FrequencySketch.class.getDeclaredField("randomSeed");
      field.setAccessible(true);
      field.setInt(sketch, RANDOM_SEED);
    } catch (Exception e) {
      Throwables.throwIfUnchecked(e);
      throw new RuntimeException(e);
    }
  }
}

@@ -684,16 +684,94 @@
 t.Field;
+%0Aimport java.util.concurrent.ConcurrentMap;%0A%0Aimport javax.annotation.Nullable;
 %0A%0Aimport
@@ -887,16 +887,21 @@
 enforce 
+that 
 a predic
@@ -1439,269 +1439,664 @@
     
-if (!(cache.asMap() instanceof BoundedLocalCache%3C?, ?%3E)) %7B%0A      return;%0A    %7D%0A%0A    BoundedLocalCache%3C?, ?%3E map = (BoundedLocalCache%3C?, ?%3E) cache.asMap();%0A    resetThreadLocalRandom();%0A    if (map.evicts()) %7B%0A      ensureRandomSeed(map.frequencySketch());%0A    %7D
+BoundedLocalCache%3C?, ?%3E map = unwrap(cache);%0A    if (map == null) %7B%0A      return;%0A    %7D%0A%0A    resetThreadLocalRandom();%0A    if (map.evicts()) %7B%0A      ensureRandomSeed(map.frequencySketch());%0A    %7D%0A  %7D%0A%0A  /** Returns the underlying bounded cache, or null if not applicable. */%0A  private static @Nullable BoundedLocalCache%3C?, ?%3E unwrap(Cache%3C?, ?%3E cache) %7B%0A    ConcurrentMap%3C?, ?%3E map = cache.asMap();%0A    if (map instanceof LocalAsyncLoadingCache.AsMapView%3C?, ?%3E) %7B%0A      map = ((LocalAsyncLoadingCache.AsMapView%3C?, ?%3E) cache.asMap()).delegate;%0A    %7D%0A    return (map instanceof BoundedLocalCache%3C?, ?%3E)%0A        ? (BoundedLocalCache%3C?, ?%3E) map%0A        : null;
 %0A  %7D

Fix flaky test by enforcing the random seeds