package org.warp.jcwdb; import java.io.IOException; import java.util.function.Function; /** * You must have only a maximum of 1 reference for each index * @param */ public class EntryReference implements Castable { private final JCWDatabase.EntryReferenceTools db; private final long entryIndex; private final DBTypeParser parser; private T value; private volatile boolean closed; private final Object closeLock = new Object(); public EntryReference(JCWDatabase.EntryReferenceTools db, long entryId, DBTypeParser parser) throws IOException { this.db = db; this.entryIndex = entryId; this.parser = parser; this.value = db.read(entryId, parser.getReader()); } public EntryReference(JCWDatabase.EntryReferenceTools db, long entryId, DBTypeParser parser, T value) { this.db = db; this.entryIndex = entryId; this.parser = parser; this.value = value; } public DBTypeParser 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.write(entryIndex, parser.getWriter(value)); } } public void editValue(Function editFunction) throws IOException { this.value = editFunction.apply(this.value); this.save(); } /** * Use editValue instead * @return */ @Deprecated() public T getValue() { return this.value; } /** * DO NOT ATTEMPT TO MODIFY THE VALUE RETURNED * @return */ public T getValueUnsafe() { return this.value; } @Override public T cast() { return (T) this; } protected void close() throws IOException { if (closed) { return; } synchronized (closeLock) { if (closed) { return; } save(); closed = true; } } public void closeWithoutSaving() { if (closed) { return; } synchronized (closeLock) { if (closed) { return; } closed = true; } } }