Flexible alternatives for locking (selective lock)

大城市里の小女人 提交于 2019-12-02 12:34:51

问题


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.


回答1:


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).



来源:https://stackoverflow.com/questions/50587897/flexible-alternatives-for-locking-selective-lock

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!