diff --git a/src/main/java/com/jakewharton/disklrucache/DiskLruCache.java b/src/main/java/com/jakewharton/disklrucache/DiskLruCache.java index e81e7fb..f4e9920 100644 --- a/src/main/java/com/jakewharton/disklrucache/DiskLruCache.java +++ b/src/main/java/com/jakewharton/disklrucache/DiskLruCache.java @@ -646,9 +646,20 @@ public synchronized void close() throws IOException { private void trimToSize() throws IOException { while (size > maxSize) { - Map.Entry toEvict = lruEntries.entrySet().iterator().next(); - remove(toEvict.getKey()); + if (!tryRemoveEntryFromOldest()) { + // cannot remove any entry (all are being edited), skip the trim + break; + } + } + } + + private boolean tryRemoveEntryFromOldest() throws IOException { + for (Map.Entry toEvict : lruEntries.entrySet()) { + if (remove(toEvict.getKey())) { + return true; + } } + return false; } /**