I'm trying to use Jake Wharton's DiskLruCache in my Android app, but I can't seem to figure out how to properly serialize and deserialize objects using the cache. Using the following code in a basic command line Java program:
DiskLruCache.Editor editor = null;
try {
editor = diskLruCache.edit("objects");
OutputStream timeOs = editor.newOutputStream(0);
OutputStream dataOs = editor.newOutputStream(1);
OutputStream timeBos = new BufferedOutputStream(timeOs);
OutputStream dataBos = new BufferedOutputStream(dataOs);
ObjectOutputStream timeOos = new ObjectOutputStream(timeBos);
ObjectOutputStream dataOos = new ObjectOutputStream(dataBos);
long createTime = System.currentTimeMillis();
String str = "testString";
ArrayList<String> list = new ArrayList<String>();
list.add("item1");
list.add("item2");
timeOos.writeLong(createTime);
// this works:
dataOos.writeObject(str);
// this does not work:
//dataOos.writeObject(list);
timeOos.close();
dataOos.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (editor != null)
try {
editor.commit();
} catch (IOException e) {
e.printStackTrace();
}
}
timeOos.writeLong(createTime)
and dataOos.writeObject(str)
successfully write data to the cache, but replacing dataOos.writeObject(str)
with dataOos.writeObject(list)
does not work. I have tried ArrayList
s and HashMap
s, and it appears that these are not serialized and written to the cache. The program executes all of the code, then hangs for around a minute before returning, leaving only the journal
file in the cache directory.
I'm not sure if this would be an issue with DiskLruCache being unable to handle container objects.
The full source and original post can be found here
EDIT (2014-01-03):
Here's a JUnit test using the Android SDK. testStoreLong()
, testStoreString()
, and testStoreArrayList()
pass but testPersistArrayListSnapshot()
and testPersistArrayListEditor()
fail.
It's a strange issue; if I put a breakpoint at line 101 (editor.commit();
) then step over, the cache file test-store-array-list.0
is not created and snapshot == null
, failing the test. But if I put a breakpoint at line 103 (DiskLruCache.Snapshot snapshot = mDiskLruCache.get("test-store-array-list");
) the file is created as expected.
Perhaps there's a bug in DiskLruCache; are there any alternative disk caching libraries that are Android-compatible?