net.intelie.pipes.util.ObjectCache Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of pipes-api Show documentation
Show all versions of pipes-api Show documentation
Intelie Pipes' API classes and interfaces
package net.intelie.pipes.util;
import java.lang.ref.WeakReference;
public class ObjectCache {
private final Bucket[] data;
private final int mask;
public ObjectCache(int bucketCount) {
Preconditions.checkArgument(Integer.bitCount(bucketCount) == 1, "Bucket count must be power of two");
this.data = new Bucket[bucketCount];
this.mask = bucketCount - 1;
}
public static int mix(int h) {
h ^= h >>> 16;
h *= 0x85ebca6b;
h ^= h >>> 13;
h *= 0xc2b2ae35;
h ^= h >>> 16;
return h;
}
public T get(B builder, CacheAdapter adapter) {
if (builder == null)
return null;
int hash = adapter.contentHashCode(builder);
int index = mix(hash) & mask;
Bucket bucket = data[index];
if (bucket != null && bucket.hash == hash) {
T cached = adapter.contentEquals(builder, data[index].get());
if (cached != null)
return cached;
}
T newValue = adapter.build(builder, this);
data[index] = new Bucket(newValue, hash);
return newValue;
}
private static final class Bucket extends WeakReference