Inceptum/common/src/main/java/io/gitlab/jfronny/inceptum/common/ObjectCache.java

40 lines
1.3 KiB
Java

package io.gitlab.jfronny.inceptum.common;
import io.gitlab.jfronny.commons.io.JFiles;
import io.gitlab.jfronny.commons.throwable.ThrowingFunction;
import io.gitlab.jfronny.commons.throwable.ThrowingSupplier;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.concurrent.ConcurrentHashMap;
public class ObjectCache {
private final ConcurrentHashMap<String, Object> container = new ConcurrentHashMap<>();
private final Path cacheDir;
public ObjectCache(Path cacheDir) {
this.cacheDir = cacheDir;
}
public void remove(String key) throws IOException {
container.remove(key);
Files.delete(cacheDir.resolve(key));
}
public void clear() throws IOException {
container.clear();
JFiles.clearDirectory(cacheDir);
}
public <T, TEx extends Throwable> T get(String key, ThrowingSupplier<String, ? extends TEx> download, ThrowingFunction<String, T, ? extends TEx> builder) throws IOException, TEx {
if (!container.containsKey(key)) {
Path cd = cacheDir.resolve(key);
if (Files.exists(cd)) container[key] = builder.apply(Files.readString(cd));
else container[key] = builder.apply(download.get());
}
//noinspection unchecked
return (T) container[key];
}
}