strangedb/src/main/java/org/warp/jcwdb/EntryReference.java

60 lines
1.1 KiB
Java
Raw Normal View History

2018-11-19 15:16:12 +01:00
package org.warp.jcwdb;
2018-11-20 18:39:48 +01:00
import java.io.IOException;
2018-11-21 01:02:25 +01:00
/**
* You must have only a maximum of 1 reference for each index
* @param <T>
*/
public class EntryReference<T> implements Castable, AutoCloseable {
2018-11-19 15:16:12 +01:00
private final JCWDatabase db;
2018-11-21 01:02:25 +01:00
private final long entryIndex;
2018-11-20 18:39:48 +01:00
private final DBTypeParser<T> parser;
2018-11-19 15:16:12 +01:00
public T value;
2018-11-21 01:02:25 +01:00
private volatile boolean closed;
private final Object closeLock = new Object();
2018-11-19 15:16:12 +01:00
2018-11-20 18:39:48 +01:00
public EntryReference(JCWDatabase db, long entryId, DBTypeParser<T> parser) throws IOException {
2018-11-19 15:16:12 +01:00
this.db = db;
2018-11-21 01:02:25 +01:00
this.entryIndex = entryId;
2018-11-19 15:16:12 +01:00
this.parser = parser;
2018-11-21 01:02:25 +01:00
this.value = db.indices.get(entryId, parser.getReader());
}
public DBTypeParser<T> getParser() {
return parser;
}
public long getIndex() {
return entryIndex;
2018-11-19 15:16:12 +01:00
}
2018-11-20 18:39:48 +01:00
public void save() throws IOException {
2018-11-21 01:02:25 +01:00
if (!closed) {
db.indices.set(entryIndex, parser.getWriter(value));
}
}
@Override
public <T> T cast() {
return (T) this;
}
@Override
public void close() throws IOException {
if (closed) {
return;
}
synchronized (closeLock) {
if (closed) {
return;
}
db.removeEntryReference(entryIndex);
save();
closed = true;
}
2018-11-19 15:16:12 +01:00
}
}