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

org.rx.core.cache.LocalCache Maven / Gradle / Ivy

There is a newer version: 3.0.0
Show newest version
package org.rx.core.cache;

import com.google.common.cache.CacheBuilder;
import lombok.SneakyThrows;
import org.rx.bean.RxConfig;
import org.rx.core.Cache;
import org.rx.util.function.BiFunc;

import java.util.Set;
import java.util.concurrent.TimeUnit;

import static org.rx.core.App.*;

public class LocalCache implements Cache {
    private final com.google.common.cache.Cache cache;

    public LocalCache() {
        this(2);
    }

    public LocalCache(int expireMinutes) {
        cache = CacheBuilder.newBuilder().maximumSize(MAX_INT)
                .expireAfterAccess(expireMinutes, TimeUnit.MINUTES)
                .expireAfterWrite(expireMinutes, TimeUnit.MINUTES).build();
    }

    @Override
    public long size() {
        return cache.size();
    }

    @Override
    public Set keySet() {
        return cache.asMap().keySet();
    }

    @Override
    public synchronized TV put(TK key, TV val) {
        TV v = cache.getIfPresent(key);
        if (v == null) {
            return null;
        }
        cache.put(key, val);
        return v;
    }

    @Override
    public synchronized TV remove(TK key) {
        TV v = cache.getIfPresent(key);
        if (v == null) {
            return null;
        }
        cache.invalidate(key);
        return v;
    }

    @Override
    public void clear() {
        cache.invalidateAll();
    }

    @Override
    public TV get(TK key) {
        return cache.getIfPresent(key);
    }

    @SneakyThrows
    @Override
    public TV get(TK key, BiFunc supplier) {
        return cache.get(key, () -> sneakyInvoke(() -> supplier.invoke(key)));
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy