strangedb/src/main/java/org/warp/jcwdb/ann/DBArrayList.java

115 lines
2.3 KiB
Java

package org.warp.jcwdb.ann;
import it.unimi.dsi.fastutil.longs.LongArrayList;
import java.io.IOError;
import java.io.IOException;
import java.util.StringJoiner;
public abstract class DBArrayList<T> extends DBObject {
private final Object indicesAccessLock = new Object();
@DBField(id = 0, type = DBDataType.UID_LIST)
private LongArrayList indices;
public DBArrayList() {
super();
}
public DBArrayList(JCWDatabase database) throws IOException {
super(database);
}
@Override
public void initialize() {
indices = new LongArrayList();
}
public T get(int index) {
synchronized (indicesAccessLock) {
try {
long uid = indices.getLong(index);
return loadItem(uid);
} catch (IOException e) {
throw new IOError(e);
}
}
}
public void add(T value) {
long uid = database.getDataLoader().allocateNullValue();
synchronized (indicesAccessLock) {
indices.add(uid);
try {
writeItemToDisk(uid, value);
} catch (IOException e) {
throw new IOError(e);
}
}
}
public void update(int index, T value) {
synchronized (indicesAccessLock) {
set(index, value);
}
}
public void set(int index, T value) {
long uid = database.getDataLoader().allocateNullValue();
synchronized (indicesAccessLock) {
indices.set(index, uid);
try {
writeItemToDisk(uid, value);
} catch (IOException e) {
throw new IOError(e);
}
}
}
public void add(int index, T value) {
long uid = database.getDataLoader().allocateNullValue();
synchronized (indicesAccessLock) {
indices.add(index, uid);
try {
writeItemToDisk(uid, value);
} catch (IOException e) {
throw new IOError(e);
}
}
}
public T getLast() {
synchronized (indicesAccessLock) {
if (indices.size() > 0) {
return get(indices.size() - 1);
} else {
return null;
}
}
}
public boolean isEmpty() {
synchronized (indicesAccessLock) {
return indices.size() <= 0;
}
}
public int size() {
synchronized (indicesAccessLock) {
return indices.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(", ", DBArrayList.class.getSimpleName() + "[", "]")
.add(indices.size() + " items")
.toString();
}
}