Skip to content

Commit

Permalink
Merge pull request #1 from google/master
Browse files Browse the repository at this point in the history
Re-initialize the cache if the directory was deleted. (google#297)
  • Loading branch information
HuterPu authored Oct 7, 2019
2 parents b95b015 + 514eac8 commit 00f072d
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 5 deletions.
20 changes: 15 additions & 5 deletions src/main/java/com/android/volley/toolbox/DiskBasedCache.java
Original file line number Diff line number Diff line change
Expand Up @@ -256,12 +256,12 @@ public synchronized void put(String key, Entry entry) {
e.size = file.length();
putEntry(key, e);
pruneIfNeeded();
return;
} catch (IOException e) {
}
boolean deleted = file.delete();
if (!deleted) {
VolleyLog.d("Could not clean up file %s", file.getAbsolutePath());
boolean deleted = file.delete();
if (!deleted) {
VolleyLog.d("Could not clean up file %s", file.getAbsolutePath());
}
initializeIfRootDirectoryDeleted();
}
}

Expand Down Expand Up @@ -295,6 +295,16 @@ public File getFileForKey(String key) {
return new File(mRootDirectorySupplier.get(), getFilenameForKey(key));
}

/** Re-initialize the cache if the directory was deleted. */
private void initializeIfRootDirectoryDeleted() {
if (!mRootDirectorySupplier.get().exists()) {
VolleyLog.d("Re-initializing cache after external clearing.");
mEntries.clear();
mTotalSize = 0;
initialize();
}
}

/** Represents a supplier for {@link File}s. */
public interface FileSupplier {
File get();
Expand Down
14 changes: 14 additions & 0 deletions src/test/java/com/android/volley/toolbox/DiskBasedCacheTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -595,6 +595,20 @@ public void publicMethods() throws Exception {
assertNotNull(DiskBasedCache.class.getMethod("getFileForKey", String.class));
}

@Test
public void initializeIfRootDirectoryDeleted() {
temporaryFolder.delete();

Cache.Entry entry = randomData(101);
cache.put("key1", entry);

assertThat(cache.get("key1"), is(nullValue()));

// confirm that we can now store entries
cache.put("key2", entry);
assertThatEntriesAreEqual(cache.get("key2"), entry);
}

/* Test helpers */

private void assertThatEntriesAreEqual(Cache.Entry actual, Cache.Entry expected) {
Expand Down

0 comments on commit 00f072d

Please sign in to comment.