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

69 lines
1.5 KiB
Java
Raw Normal View History

2018-11-19 15:16:12 +01:00
package org.warp.jcwdb;
import com.esotericsoftware.kryo.io.Output;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
2018-11-20 18:39:48 +01:00
import java.nio.ByteBuffer;
2018-11-19 15:16:12 +01:00
import java.nio.channels.Channels;
2018-11-20 18:39:48 +01:00
import java.nio.channels.FileChannel;
2018-11-19 15:16:12 +01:00
import java.nio.channels.SeekableByteChannel;
import java.util.*;
2018-11-21 01:02:25 +01:00
public class FileAllocator implements AutoCloseable {
2018-11-20 18:39:48 +01:00
private final SeekableByteChannel dataFileChannel;
private volatile long allocableOffset;
private volatile boolean closed;
private final Object closeLock = new Object();
2018-11-22 23:31:41 +01:00
private final Object allocateLock = new Object();
2018-11-20 18:39:48 +01:00
public FileAllocator(SeekableByteChannel dataFileChannel) throws IOException {
this.dataFileChannel = dataFileChannel;
this.allocableOffset = this.dataFileChannel.size();
}
2018-11-19 15:16:12 +01:00
/**
2018-11-20 18:39:48 +01:00
* TODO: not implemented
* @param size
* @return offset
2018-11-19 15:16:12 +01:00
*/
2018-11-20 18:39:48 +01:00
public long allocate(int size) {
checkClosed();
2018-11-22 23:31:41 +01:00
synchronized (allocateLock) {
long allocatedOffset = allocableOffset;
allocableOffset += size;
return allocatedOffset;
}
2018-11-19 15:16:12 +01:00
}
2018-11-20 18:39:48 +01:00
public void close() throws IOException {
if (closed) {
return;
}
synchronized (closeLock) {
if (closed) {
return;
}
closed = true;
}
2018-11-19 15:16:12 +01:00
}
2018-11-20 18:39:48 +01:00
2018-11-19 15:16:12 +01:00
/**
2018-11-20 18:39:48 +01:00
* Frees the unused bytes
* @param startPosition
* @param length
2018-11-19 15:16:12 +01:00
*/
2018-11-20 18:39:48 +01:00
public void markFree(long startPosition, int length) {
checkClosed();
// TODO: advanced feature, not implemented.
2018-11-19 15:16:12 +01:00
}
2018-11-20 18:39:48 +01:00
private void checkClosed() {
if (closed) {
throw new RuntimeException("Index Manager is closed.");
}
2018-11-19 15:16:12 +01:00
}
}