[main] FileBackedRef from Inceptum
This commit is contained in:
parent
58fa5c5620
commit
edc66800e1
|
@ -0,0 +1,48 @@
|
|||
package io.gitlab.jfronny.commons.cache;
|
||||
|
||||
import io.gitlab.jfronny.commons.io.JFiles;
|
||||
|
||||
import java.io.Closeable;
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Type;
|
||||
import java.nio.file.*;
|
||||
|
||||
/**
|
||||
* Maintains an object reference backed by a file and re-creates it automatically upon change
|
||||
* @param <T> The type of the referenced object
|
||||
*/
|
||||
public class FileBackedRef<T> implements Closeable {
|
||||
private final Path filePath;
|
||||
private final Type type;
|
||||
private final WatchService service;
|
||||
private T cache = null;
|
||||
|
||||
public FileBackedRef(Path filePath, Type type) throws IOException {
|
||||
this.filePath = filePath;
|
||||
this.type = type;
|
||||
this.service = FileSystems.getDefault().newWatchService();
|
||||
filePath.getParent().register(service, StandardWatchEventKinds.ENTRY_MODIFY);
|
||||
}
|
||||
|
||||
public FileBackedRef(Path filePath, Class<T> type) throws IOException {
|
||||
this(filePath, (Type) type);
|
||||
}
|
||||
|
||||
public T get() throws IOException {
|
||||
WatchKey key = service.poll();
|
||||
boolean update = cache == null;
|
||||
if (key != null) {
|
||||
for (WatchEvent<?> event : key.pollEvents()) {
|
||||
update |= event.context().equals(filePath);
|
||||
}
|
||||
key.reset();
|
||||
}
|
||||
if (update) cache = JFiles.readObject(filePath, type);
|
||||
return cache;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
service.close();
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue