Example usage for com.google.common.cache CacheBuilder maximumSize

List of usage examples for com.google.common.cache CacheBuilder maximumSize

Introduction

In this page you can find the example usage for com.google.common.cache CacheBuilder maximumSize.

Prototype

long maximumSize

To view the source code for com.google.common.cache CacheBuilder maximumSize.

Click Source Link

Usage

From source file:org.apache.kylin.dict.CachedTreeMap.java

private CachedTreeMap(int maxCount, Class<K> keyClazz, Class<V> valueClazz, String basePath, boolean immutable,
        int maxVersions, long versionTTL) throws IOException {
    super();//  ww w .java  2s. c  o m
    this.keyClazz = keyClazz;
    this.valueClazz = valueClazz;
    this.immutable = immutable;
    this.keepAppend = true;
    this.maxVersions = maxVersions;
    this.versionTTL = versionTTL;
    this.conf = new Configuration();
    if (basePath.endsWith("/")) {
        basePath = basePath.substring(0, basePath.length() - 1);
    }
    this.baseDir = new Path(basePath);
    this.fs = FileSystem.get(baseDir.toUri(), conf);
    if (!fs.exists(baseDir)) {
        fs.mkdirs(baseDir);
    }
    this.versionDir = getLatestVersion(conf, fs, baseDir);
    this.workingDir = new Path(baseDir, "working");
    if (!this.immutable) {
        // For mutable map, copy all data into working dir and work on it, avoiding suddenly server crash made data corrupt
        if (fs.exists(workingDir)) {
            fs.delete(workingDir, true);
        }
        FileUtil.copy(fs, versionDir, fs, workingDir, false, true, conf);
    }
    CacheBuilder builder = CacheBuilder.newBuilder().removalListener(new RemovalListener<K, V>() {
        @Override
        public void onRemoval(RemovalNotification<K, V> notification) {
            logger.info(String.format("Evict cache key %s(%d) with value %s caused by %s, size %d/%d ",
                    notification.getKey(), notification.getKey().hashCode(), notification.getValue(),
                    notification.getCause(), size(), valueCache.size()));
            switch (notification.getCause()) {
            case SIZE:
                writeValue(notification.getKey(), notification.getValue());
                break;
            case EXPLICIT:
                deleteValue(notification.getKey());
                break;
            default:
            }
        }
    });
    if (this.immutable) {
        // For immutable values, load all values as much as possible, and evict by soft reference to free memory when gc
        builder.softValues();
    } else {
        builder.maximumSize(maxCount);
    }
    this.valueCache = builder.build(new CacheLoader<K, V>() {
        @Override
        public V load(K key) throws Exception {
            V value = readValue(key);
            logger.info(String.format("Load cache by key %s(%d) with value %s", key, key.hashCode(), value));
            return value;
        }
    });
}