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

com.clickhouse.client.cache.JdkLruCache Maven / Gradle / Ivy

There is a newer version: 0.6.5
Show newest version
package com.clickhouse.client.cache;

import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;

import com.clickhouse.client.ClickHouseCache;

/**
 * A simple thread-safe LRU cache based on LinkedHashMap. It's not as effient as
 * the one in Caffeine/Guava, but it requires no extra dependency.
 */
public class JdkLruCache implements ClickHouseCache {
    static class LruCacheMap extends LinkedHashMap {
        private final int capacity;

        protected LruCacheMap(int capacity) {
            super(capacity, 0.75f, true);

            this.capacity = capacity;
        }

        @Override
        protected boolean removeEldestEntry(Map.Entry eldest) {
            return size() > capacity;
        }
    }

    /**
     * Creates a cache with given capacity and load function.
     *
     * @param       type of the key
     * @param       type of the value
     * @param capacity capacity
     * @param loadFunc load function
     * @return cache
     */
    public static  ClickHouseCache create(int capacity, Function loadFunc) {
        return new JdkLruCache<>(new LruCacheMap<>(capacity), loadFunc);
    }

    private final Map cache;
    private final Function loadFunc;

    protected JdkLruCache(Map cache, Function loadFunc) {
        if (cache == null || loadFunc == null) {
            throw new IllegalArgumentException("Non-null cache and load function are required");
        }
        this.cache = Collections.synchronizedMap(cache);
        this.loadFunc = loadFunc;
    }

    @Override
    public V get(K key) {
        return cache.computeIfAbsent(key, loadFunc);
    }

    @Override
    public  T unwrap(Class clazz) {
        return Objects.requireNonNull(clazz, "Non-null class is required").cast(cache);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy