Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Re-initialize the cache if the directory was deleted. #297

Merged
merged 3 commits into from
Oct 3, 2019
Merged
Show file tree
Hide file tree
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
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