forked from mitmel/Android-Image-Cache
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKeyedLock.java
More file actions
78 lines (63 loc) · 1.94 KB
/
Copy pathKeyedLock.java
File metadata and controls
78 lines (63 loc) · 1.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package edu.mit.mobile.android.imagecache;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;
import android.util.Log;
/**
* A synchronization lock that creates a separate lock for each key.
*
* @author <a href="mailto:spomeroy@mit.edu">Steve Pomeroy</a>
*
* @param <K>
*/
public class KeyedLock<K> {
private static final String TAG = KeyedLock.class.getSimpleName();
private final Map<K, ReentrantLock> mLocks = new HashMap<K, ReentrantLock>();
private static boolean DEBUG = false;
/**
* @param key
*/
public void lock(K key) {
if (DEBUG) {
log("acquiring lock for key " + key);
}
ReentrantLock lock;
synchronized (mLocks) {
lock = mLocks.get(key);
if (lock == null) {
lock = new ReentrantLock();
mLocks.put(key, lock);
if (DEBUG) {
log(lock + " created new lock and added it to map");
}
}
}
lock.lock();
}
/**
* @param key
*/
public void unlock(K key) {
if (DEBUG) {
log("unlocking lock for key " + key);
}
ReentrantLock lock;
synchronized (mLocks) {
lock = mLocks.get(key);
if (lock == null) {
Log.e(TAG, "Attempting to unlock lock for key " + key + " which has no entry");
return;
}
if (DEBUG) {
log(lock + " has queued threads " + lock.hasQueuedThreads() + " for key " + key);
}
// maybe entries should be removed when there are no queued threads. This would
// occasionally fail...
// final boolean queued = lock.hasQueuedThreads();
lock.unlock();
}
}
private void log(String message) {
Log.d(TAG, Thread.currentThread().getId() + "\t" + message);
}
}