org.rx.core.cache.LocalCache Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of rxlib Show documentation
Show all versions of rxlib Show documentation
A set of utilities for Java
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)));
}
}