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

90 lines
1.7 KiB
Java

package org.warp.jcwdb;
import java.io.IOException;
/**
* You must have only a maximum of 1 reference for each index
* @param <T>
*/
public class EntryReference<T> implements Castable, AutoCloseable {
private final JCWDatabase db;
private final long entryIndex;
private final DBTypeParser<T> parser;
public T value;
private volatile boolean closed;
private final Object closeLock = new Object();
public EntryReference(JCWDatabase db, long entryId, DBTypeParser<T> parser) throws IOException {
this.db = db;
this.entryIndex = entryId;
this.parser = parser;
this.value = db.getIndexManager().get(entryId, parser.getReader());
}
public EntryReference(JCWDatabase db, long entryId, DBTypeParser<T> parser, T value) {
this.db = db;
this.entryIndex = entryId;
this.parser = parser;
this.value = value;
}
public DBTypeParser<T> getParser() {
return parser;
}
public long getIndex() {
return entryIndex;
}
public long calculateHash() {
return parser.calculateHash(value);
}
/**
* Note that this method won't be called when closing without saving
* @throws IOException
*/
public void save() throws IOException {
if (!closed) {
db.getIndexManager().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;
}
save();
db.removeEntryReference(entryIndex);
closed = true;
}
}
public void closeWithoutSaving() {
if (closed) {
return;
}
synchronized (closeLock) {
if (closed) {
return;
}
db.removeEntryReference(entryIndex);
closed = true;
}
}
}