简单的基于 Java 名称的锁? [英] Simple Java name based locks?
问题描述
MySQL 有一个方便的功能:
MySQL has a handy function:
SELECT GET_LOCK("SomeName")
这可用于为应用程序创建简单但非常具体的基于名称的锁.但是,它需要一个数据库连接.
This can be used to create simple, but very specific, name-based locks for an application. However, it requires a database connection.
我有很多情况,例如:
someMethod() {
// do stuff to user A for their data for feature X
}
简单的同步这个方法是没有意义的,因为,比如如果同时为用户B调用了这个方法,用户B就不需要等待用户A完成才开始,只需要操作用户A和特征X组合需要等待.
It doesn't make sense to simply synchronize this method, because, for example, if this method is called for user B in the meantime, user B does not need to wait for user A to finish before it starts, only operations for the user A and feature X combination need to wait.
使用 MySql 锁,我可以执行以下操作:
With the MySql lock I could do something like:
someMethod() {
executeQuery("SELECT GET_LOCK('userA-featureX')")
// only locked for user A for their data for feature X
executeQuery("SELECT RELEASE_LOCK('userA-featureX')")
}
由于 Java 锁定是基于对象的,因此似乎我需要创建一个新对象来表示此锁定的情况,然后将其放入某个静态缓存中,以便所有线程都可以看到它.针对这种情况的后续锁定请求将在缓存中定位锁定对象并获取其锁定.我试图创建这样的东西,但是锁缓存本身需要同步.此外,很难检测到何时不再使用锁定对象以便将其从缓存中删除.
Since Java locking is based on objects, it seems like I would need to create a new object to represent the situation for this lock and then put it in a static cache somewhere so all the threads can see it. Subsequent requests to lock for that situation would then locate the lock object in the cache and acquire its lock. I tried to create something like this, but then the lock cache itself needs synchronization. Also, it is difficult to detect when a lock object is no longer being used so that it can be removed from the cache.
我查看了 Java 并发包,但没有什么能处理这样的事情.有没有简单的方法来实现这一点,还是我从错误的角度看待这个问题?
I have looked at the Java concurrent packages, but nothing stands out as being able to handle something like this. Is there an easy way to implement this, or am I looking at this from the wrong perspective?
澄清一下,我不想提前创建预定义的锁池,我想按需创建它们.我想到的一些伪代码是:
To clarify, I am not looking to create a predefined pool of locks ahead of time, I would like to create them on demand. Some pseudo-code for what I am thinking of is:
LockManager.acquireLock(String name) {
Lock lock;
synchronized (map) {
lock = map.get(name);
// doesn't exist yet - create and store
if(lock == null) {
lock = new Lock();
map.put(name, lock);
}
}
lock.lock();
}
LockManager.releaseLock(String name) {
// unlock
// if this was the last hold on the lock, remove it from the cache
}
推荐答案
也许这对你有用:jkeylockmanager一个>
我最初的回答可能有点短.我是作者,多次遇到这个问题,但找不到现有的解决方案.这就是我在 Google Code 上创建这个小型库的原因.
My initial response was probably a bit short. I am the author and was faced with this problem several times and could not find an existing solution. That's why I made this small library on Google Code.
这篇关于简单的基于 Java 名称的锁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!