Skip to content
This repository has been archived by the owner on Jul 21, 2023. It is now read-only.

Commit

Permalink
Don't append to a truncated line in the journal.
Browse files Browse the repository at this point in the history
  • Loading branch information
swankjesse committed Oct 24, 2014
1 parent c2965c0 commit 5b45d10
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 2 deletions.
10 changes: 8 additions & 2 deletions src/main/java/com/jakewharton/disklrucache/DiskLruCache.java
Expand Up @@ -224,8 +224,6 @@ public static DiskLruCache open(File directory, int appVersion, int valueCount,
try {
cache.readJournal();
cache.processJournal();
cache.journalWriter = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(cache.journalFile, true), Util.US_ASCII));
return cache;
} catch (IOException journalIsCorrupt) {
System.out
Expand Down Expand Up @@ -272,6 +270,14 @@ private void readJournal() throws IOException {
}
}
redundantOpCount = lineCount - lruEntries.size();

// If we ended on a truncated line, rebuild the journal before appending to it.
if (reader.hasUnterminatedLine()) {
rebuildJournal();
} else {
journalWriter = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(journalFile, true), Util.US_ASCII));
}
} finally {
Util.closeQuietly(reader);
}
Expand Down
Expand Up @@ -176,6 +176,10 @@ public String toString() {
}
}

public boolean hasUnterminatedLine() {
return end == -1;
}

/**
* Reads new input data into the buffer. Call only with pos == end or end == -1,
* depending on the desired outcome if the function throws.
Expand Down
Expand Up @@ -375,6 +375,12 @@ public final class DiskLruCacheTest {
writer.close();
cache = DiskLruCache.open(cacheDir, appVersion, 2, Integer.MAX_VALUE);
assertThat(cache.get("k1")).isNull();

// The journal is not corrupt when editing after a truncated line.
set("k1", "C", "D");
cache.close();
cache = DiskLruCache.open(cacheDir, appVersion, 2, Integer.MAX_VALUE);
assertValue("k1", "C", "D");
}

@Test public void openWithTooManyFileSizesClearsDirectory() throws Exception {
Expand Down

0 comments on commit 5b45d10

Please sign in to comment.