DiskLruCache icon indicating copy to clipboard operation
DiskLruCache copied to clipboard

Lost cache in some condition

Open teoking opened this issue 12 years ago • 7 comments

I found an issue: you created a new cache and just then the app is crashed, the cache will be lost.

I check the journal file and found that: the new cache you just created is marked with "DIRTY", and even if I called commit, there's no "CLEAN" followed that "DIRTY", at this time, if the app crashes, the cache leaves "DIRTY" but not "CLEAN" which it should be. Then you launch the app again, the "DIRTY" cache with no "CLEAN" followed will be deleted, and you lost the cache.

This scenario cannot covered by android test cases.

I found this may be caused by the journal is opened by BufferedWriter which has a 8K buffer internally. So the latest "CLEAN" state is actually in the buffer but not in disk when the crash happens.

Add the following line in completeEdit method seems can solve this: journalWriter.flush();

teoking avatar Sep 18 '12 14:09 teoking

This is a policy decision in the API. You can manually call flush() in your own code if you'd like to flush the journal after every write. DiskLruCache doesn't do this by default because it wants to minimize the number of slow disk writes it makes.

swankjesse avatar Sep 18 '12 15:09 swankjesse

That said, this does need to be documented!

swankjesse avatar Sep 18 '12 15:09 swankjesse

I see your point. I'd like not flush journal after every write, only after write "CLEAN" or "DIRTY", while not flush after write "READ"(not worth to do). Back to my case, my app is an android app which may be closed or interrupted unpredictably, and I has only one chance to create a cache(after a video is downloaded) and use it elsewhere. If someone has the similar case with me, I suggest flush after every commit immediately.

teoking avatar Sep 19 '12 01:09 teoking

@swankjesse could you suggest where it is better to flush DiskLruCache for Android apps to prevent loosing of image cache after app close or crash?

lexer avatar Feb 04 '13 09:02 lexer

Calling flush after committing an edit would work.

swankjesse avatar Feb 04 '13 13:02 swankjesse

Thanks!

lexer avatar Feb 04 '13 14:02 lexer

Thank you so much for this, flush works!

kroikie avatar Aug 20 '13 11:08 kroikie