Reputation: 7543
I need to resolve situation for equal objects with different memory location (it happens for REST request because of multithreading).
So as part solution I have implemented service. I'm sharing here most important parts:
private Map<T, ReentrantLock> lockHolder = new HashMap();
void unLock(T monitorMarker) {
synchronized (lockHolder) {
ReentrantLock lock = lockHolder.get(monitorMarker);
if (lock == null || lock.getHoldCount() == 0) {
return;
}
lock.unlock();
if (lock.getHoldCount() == 0) {
lockHolder.remove(monitorMarker);
}
}
}
ReentrantLock getLockForCalendar(T monitorMarker) {
synchronized(monitorMarker) {
ReentrantLock lock = lockHolder.get(monitorMarker);
if (lock == null) {
lock = new ReentrantLock();
lockHolder.put(monitorMarker, lock);
}
return lock;
}
}
in general it works without problems.
Right now I need to map this util on domain metadata (solution could be using Map<String, Map<Object, Lock>>
or cache injecting and nothing unresolvable)...
I prefer to use JDK util or open source util with similar solution because they already provide handling this cases... I believe a lot of developers faced with similar issues and solution should be present in open source libraries. I've researched spring
utilities, apache
utilities some google
libraries but I haven't found satisfactory result.
Suggest me consider right library(s) to use please.
Upvotes: 1
Views: 564
Reputation: 73528
Guava's Striped lock implementation does what you're doing, but properly (and with far more options regarding weak locks, laziness, semaphores instead of locks etc.).
It's not that different from what you've done, but you've combined synchronized
with locks, whereas a ConcurrentHashMap
can get rid of the explicit synchronization (and provide some performance benefits by not locking the whole map every time it's accessed).
Upvotes: 1