37
37
*/
38
38
public abstract class LimitedDiscCache extends BaseDiscCache {
39
39
40
+ private static final int INVALID_READ_SIZE = -1 ;
41
+
40
42
private final AtomicInteger cacheSize ;
41
43
42
44
private final int sizeLimit ;
@@ -88,9 +90,10 @@ public void run() {
88
90
public void put (String key , File file ) {
89
91
int valueSize = getSize (file );
90
92
int curCacheSize = cacheSize .get ();
93
+
91
94
while (curCacheSize + valueSize > sizeLimit ) {
92
95
int freedSize = removeNext ();
93
- if (freedSize == 0 ) break ; // cache is empty (have nothing to delete)
96
+ if (freedSize == INVALID_READ_SIZE ) break ; // cache is empty (have nothing to delete)
94
97
curCacheSize = cacheSize .addAndGet (-freedSize );
95
98
}
96
99
cacheSize .addAndGet (valueSize );
@@ -121,9 +124,8 @@ public void clear() {
121
124
/** Remove next file and returns it's size */
122
125
private int removeNext () {
123
126
if (lastUsageDates .isEmpty ()) {
124
- return 0 ;
127
+ return INVALID_READ_SIZE ;
125
128
}
126
-
127
129
Long oldestUsage = null ;
128
130
File mostLongUsedFile = null ;
129
131
Set <Entry <File , Long >> entries = lastUsageDates .entrySet ();
@@ -143,11 +145,17 @@ private int removeNext() {
143
145
}
144
146
145
147
int fileSize = getSize (mostLongUsedFile );
146
- if (mostLongUsedFile .delete ()) {
148
+
149
+ if (!mostLongUsedFile .exists ()) {
150
+ lastUsageDates .remove (mostLongUsedFile );
151
+ return 0 ;
152
+ }
153
+
154
+ if ( mostLongUsedFile .delete ()) {
147
155
lastUsageDates .remove (mostLongUsedFile );
148
156
}
149
157
return fileSize ;
150
158
}
151
159
152
160
protected abstract int getSize (File file );
153
- }
161
+ }
0 commit comments