Skip to content
This repository has been archived by the owner on Oct 25, 2024. It is now read-only.

DBR-204 support writing asynchronously #210

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 17 additions & 4 deletions tape/src/main/java/com/squareup/tape2/QueueFile.java
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ public final class QueueFile implements Closeable, Iterable<byte[]> {

@Private boolean closed;

@Private static RandomAccessFile initializeFromFile(File file, boolean forceLegacy)
@Private static void initializeFromFile(File file, boolean forceLegacy)
throws IOException {
if (!file.exists()) {
// Use a temp file so we don't leave a partially-initialized file.
Expand All @@ -157,15 +157,18 @@ public final class QueueFile implements Closeable, Iterable<byte[]> {
throw new IOException("Rename failed!");
}
}

return open(file);
}

/** Opens a random access file that writes synchronously. */
private static RandomAccessFile open(File file) throws FileNotFoundException {
return new RandomAccessFile(file, "rwd");
}

/** Opens a random access file that writes asynchronously. */
private static RandomAccessFile openAsynchronously(File file) throws FileNotFoundException {
return new RandomAccessFile(file, "rw");
}

QueueFile(File file, RandomAccessFile raf, boolean zero, boolean forceLegacy) throws IOException {
this.file = file;
this.raf = raf;
Expand Down Expand Up @@ -723,6 +726,7 @@ public static final class Builder {
final File file;
boolean zero = true;
boolean forceLegacy = false;
boolean writeSynchronously = true;

/** Start constructing a new queue backed by the given file. */
public Builder(File file) {
Expand All @@ -744,12 +748,21 @@ public Builder forceLegacy(boolean forceLegacy) {
return this;
}

/**
* When false, writing to file is asynchronous
*/
public Builder writeSynchronously(boolean writeSynchronously) {
this.writeSynchronously = writeSynchronously;
return this;
}

/**
* Constructs a new queue backed by the given builder. Only one instance should access a given
* file at a time.
*/
public QueueFile build() throws IOException {
RandomAccessFile raf = initializeFromFile(file, forceLegacy);
initializeFromFile(file, forceLegacy);
RandomAccessFile raf = writeSynchronously ? open(file) : openAsynchronously(file);
QueueFile qf = null;
try {
qf = new QueueFile(file, raf, zero, forceLegacy);
Expand Down