How to acquire a lock by a key(如何通过钥匙获得锁)
问题描述
在不锁定整个集合的情况下,防止同时更新键值集中的一条记录的最佳方法是什么?从语义上讲,我正在寻找某种按键锁定(理想情况下,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.)
这篇关于如何通过钥匙获得锁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何通过钥匙获得锁
基础教程推荐
- 如何对 HashSet 进行排序? 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01