如何通过钥匙获得锁
在不锁定整个集合的情况下,防止同时更新键值集中的一条记录的最佳方法是什么?从语义上讲,我正在寻找某种按键锁定(理想情况下,Java 实现,但不一定):
What is the best way to prevent concurrent update of one record in a key-value set without locking the entire set? Semantically, I'm looking for some kind of locking by a key (ideally, Java implementation, but not necessarily):
interface LockByKey {
void lock(String key); // acquire an exclusive lock for a key
void unlock(String key); // release lock for a key
}
此锁旨在同步对远程存储的访问,因此不能选择某些同步的 Java 集合.
This lock is intended to synchronize an access to a remote store, so some synchronized Java collection is not an option.
推荐答案
Guava 在 13.0 中发布了类似的东西;如果你愿意,你可以把它从 HEAD 中取出.
Guava has something like this being released in 13.0; you can get it out of HEAD if you like.
Stripe<Lock>
或多或少分配特定数量的锁,然后根据其哈希码将字符串分配给锁.API 看起来或多或少像
Striped<Lock>
more or less allocates a specific number of locks, and then assigns strings to locks based on their hash code. The API looks more or less like
Striped<Lock> locks = Striped.lock(stripes);
Lock l = locks.get(string);
l.lock();
try {
// do stuff
} finally {
l.unlock();
}
或多或少,可控制的条带数量让您可以用内存使用来交换并发性,因为为每个字符串键分配一个完整的锁可能会很昂贵;从本质上讲,只有在发生哈希冲突时才会出现锁争用,而这种情况(可以预见的)很少见.
More or less, the controllable number of stripes lets you trade concurrency against memory usage, because allocating a full lock for each string key can get expensive; essentially, you only get lock contention when you get hash collisions, which are (predictably) rare.
(披露:我为 Guava 做出了贡献.)
(Disclosure: I contribute to Guava.)
相关文章