Skip to content
This repository has been archived by the owner on Jul 21, 2023. It is now read-only.

Concurrent edit experience is cumbersome #19

Open
swankjesse opened this issue Sep 20, 2012 · 2 comments
Open

Concurrent edit experience is cumbersome #19

swankjesse opened this issue Sep 20, 2012 · 2 comments

Comments

@swankjesse
Copy link
Collaborator

We're using DiskLruCache in a serverside app that downloads images from a remote server. When two requests simultaneously want to store the same image in the cache, the code gets very ugly very fast. The problem is that edit() returns null and we have no mechanism to wait on the other editor's download to complete.

It would be handy if there was an API to await a snapshot that's currently being created.

I think it would be relatively straightforward to implement this on top of Guava's LoadingCache, but it would be simpler code to just do the blocking mechanics directly in DiskLruCache.

@chrisbanes
Copy link

The way I've implemented this is to keep a Map of ReentrantLocks. Feels a bit hacky but it seems to be working.

HashMap<String, ReentrantLock> mDiskCacheEditLocks = new HashMap<String, ReentrantLock>();

final ReentrantLock lock = getLockForDiskCacheEdit(key);
lock.lock();
try {
    DiskLruCache.Editor editor = mDiskCache.edit(key);
    // blah
    editor.commit();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    lock.unlock();
}

private ReentrantLock getLockForDiskCacheEdit(String key) {
    synchronized (mDiskCacheEditLocks) {
        ReentrantLock lock = mDiskCacheEditLocks.get(key);
        if (null == lock) {
            lock = new ReentrantLock();
            mDiskCacheEditLocks.put(key, lock);
        }
        return lock;
    }
}

@virl
Copy link

virl commented May 2, 2015

@chrisbanes uh what an ugly code. Why does this lib not supporting this from the box like TMCache? :(

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants