灵活的锁定选择(选择性锁定) [英] Flexible alternatives for locking (selective lock)

查看:131
本文介绍了灵活的锁定选择(选择性锁定)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要解决具有不同内存位置的相等对象的情况(由于多线程,REST请求会发生这种情况.)

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;
    }
}

通常它没有问题.

现在,我需要将此util映射到域元数据(解决方案可以使用Map<String, Map<Object, Lock>>或缓存注入,没有无法解决的问题)...

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

我更喜欢将JDK util或开源util与类似的解决方案一起使用,因为他们已经提供了处理这种情况的方法.我相信很多面临类似问题的开发人员都应该在开源库中找到解决方案.我已经研究了spring实用程序,apache实用程序一些google库,但是没有找到令人满意的结果.

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.

推荐答案

番石榴的

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

这与您所做的没什么不同,但是您已经将synchronized与锁结合在一起,而ConcurrentHashMap可以摆脱显式同步(并且通过不每次都锁定整个地图而提供了一些性能优势)时间).

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

这篇关于灵活的锁定选择(选择性锁定)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆