Permalink
Browse files

- Added setNewFile for changing a BloomFilter's file on disk

  • Loading branch information...
1 parent 4a862ef commit f89bef87430b83b1689396ecbd99cc1465a1c527 @mikecvet mikecvet committed Jul 13, 2011
Showing with 44 additions and 2 deletions.
  1. +44 −2 src/main/java/com/greplin/bloomfilter/BloomFilter.java
@@ -54,15 +54,15 @@ public void close(byte[] cache) {
}
};
- private final RandomAccessFile file;
+ private RandomAccessFile file;
private byte[] cache = null;
// Note: unflushedChanges is always implemented as a ConcurrentSkipListMap for a few reasons
// First, iteration is ordered based on its keys, and its more efficient to seek to each change in order
// Second, because it's always small (elements<SEEK_THRESHOLD) the O(log(N)) operations aren't a big deal,
// and are almost always outweighed by benefits of being lock-free.
// One caveat is that the size() method is O(n) time, so we keep an independent size counter.
- private final Map<Integer, Byte> unflushedChanges;
+ private Map<Integer, Byte> unflushedChanges;
private final AtomicInteger unflushedChangeCounter = new AtomicInteger(0);
private volatile boolean cacheDirty;
@@ -612,6 +612,48 @@ private void modifyBucket(int position, boolean decr) {
/**
+ * Closes this BloomFilter and sets its file to the given File instead. If the given file already exists and
+ * force is true, deletes the existing file first.
+ *
+ * @param f The file to save this BloomFilter to on disk
+ * @param force If true, forces the existing file for this BloomFilter to be deleted
+ * @throws IOException If a problem occurs deleting the old file or creating the new one
+ */
+ public void setNewFile(File f, boolean force) throws IOException {
+
+ close();
+
+ if (f != null) {
+ if (f.exists()) {
+ if (force) {
+ if (!f.delete()) {
+ throw new IOException("Couldn't delete old file at " + f.getAbsolutePath());
+ }
+ } else {
+ throw new IllegalArgumentException("Can't create a new BloomFilter at " + f.getAbsolutePath()
+ + " since it already exists");
+ }
+ }
+
+ this.file = new RandomAccessFile(f, "rw");
+ this.metadata.writeToFile(this.file);
+ this.file.setLength(this.metadata.getTotalLength());
+ this.file.getFD().sync();
+
+ if (this.unflushedChanges == null) {
+ unflushedChanges = new ConcurrentSkipListMap<Integer, Byte>();
+ } else {
+ this.unflushedChanges.clear();
+ }
+
+ if (f.length() != this.metadata.getTotalLength()) {
+ throw new RuntimeException("Bad size - expected " + this.metadata.getTotalLength() + " but got " + f.length());
+ }
+ }
+ }
+
+
+ /**
* Increments the count in a given bucket
*
* @param bucket - which bucket to increment

0 comments on commit f89bef8

Please sign in to comment.