package it.cavallium.strangedb.lists; import it.unimi.dsi.fastutil.longs.LongArrayList; import it.cavallium.strangedb.EnhancedObject; import it.cavallium.strangedb.database.IDatabaseTools; import java.io.IOException; import java.util.StringJoiner; public abstract class StrandeDbList extends EnhancedObject { private final Object indicesAccessLock = new Object(); protected abstract LongArrayList getIndices(); public StrandeDbList() { } public StrandeDbList(IDatabaseTools databaseTools) throws IOException { super(databaseTools); } public T get(int index) throws IOException { synchronized (indicesAccessLock) { long uid = getIndices().getLong(index); return loadItem(uid); } } public void add(T value) throws IOException { long uid = databaseTools.getObjectsIO().newNullObject(); synchronized (indicesAccessLock) { getIndices().add(uid); writeItemToDisk(uid, value); } } public void update(int index, T value) throws IOException { synchronized (indicesAccessLock) { long uid = getIndices().getLong(index); writeItemToDisk(uid, value); } } public void set(int index, T value) throws IOException { long uid = databaseTools.getObjectsIO().newNullObject(); synchronized (indicesAccessLock) { getIndices().set(index, uid); writeItemToDisk(uid, value); } } public void add(int index, T value) throws IOException { long uid = databaseTools.getObjectsIO().newNullObject(); synchronized (indicesAccessLock) { getIndices().add(index, uid); writeItemToDisk(uid, value); } } public T getLast() throws IOException { synchronized (indicesAccessLock) { if (getIndices().size() > 0) { return get(getIndices().size() - 1); } else { return null; } } } public boolean isEmpty() { synchronized (indicesAccessLock) { return getIndices().size() <= 0; } } public int size() { synchronized (indicesAccessLock) { return getIndices().size(); } } protected abstract T loadItem(long uid) throws IOException; protected abstract void writeItemToDisk(long uid, T item) throws IOException; @Override public String toString() { return new StringJoiner(", ", StrandeDbList.class.getSimpleName() + "[", "]") .add(getIndices().size() + " items") .toString(); } }