All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.intelie.pipes.util.ObjectCache Maven / Gradle / Ivy

There is a newer version: 0.25.5
Show newest version
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 {
        private final int hash;

        private Bucket(Object value, int hash) {
            super(value);
            this.hash = hash;
        }
    }
}