Reputation: 16671
I want to have a second lock around a map which is of type Collections.synchronizedMap. How can I have it?
Upvotes: 0
Views: 186
Reputation: 262834
private ReadWriteLock mapLock = new ReentrantReadWriteLock();
mapLock.writeLock().lock();
try {
final TableManagementInfo table = TABLES.get(mKey);
Am i doing wrong..??
Depends what you are trying to do and what code follows.
You should probably finally unlock()
. But then one has to ask why you do not want to use a synchronized
block instead (see the answer by @WhiteFang34).
Also, if all you are doing in the critical section is calling a single get on an already concurrent map, you don't need the extra lock.
If on the other hand, you do other things, you probably don't need to use a synchronized map (with its insufficient locking) in the first place (just use your outer lock if you can do so in all places where the map is used).
To sum up, you do not want to use ReadWriteLock when a synchronized block will do, and you do not want to use two locks where one will do (use either SynchronizedMap or the application-level lock, but not both).
Upvotes: 1
Reputation: 72079
It's not clear why you want to do this, but here's essentially how:
private Map map = Collections.synchronizedMap(new HashMap());
private Object lock = new Object();
public void someMethod() {
synchronized (lock) {
// access map here
}
}
Upvotes: 2