Lets say I have a FooClass
, which has an id
with type long:
public class FooClass {
long id;
}
There is a method in whatever class with similar signature:
public void shouldBeSynchronizedForAFooClassId(long fooClassId) {
//does something
}
What could I do:
FooClass
with id
1 and FooClass
with id
2 can run parallel without problem. Map
with id as key and a monitored Object
as value. This case I have to suffer with registering the number of threads using the same monitored Object to be able to cleanup the monitored Objects as soon as they are not used by any thread anymore. I thought, there must be a readymade solution like:
Is there something like this out of the box in some library?
您可以使用所需的工具,但必须自己组装解决方案,例如ReentrantLocks 的映射
There isn't, as far as I know, any ready-made solution to the problem you're facing in the JDK.
But Guava has Striped , which does almost what you want. It doesn't associate a lock per ID, but rather a lock per "stripe" of IDs. That should be sufficient to avoid contention.
Instead of long id
, you could have ID id;
where ID
is a class that you define. Then you can simply lock the id
object.
Your ID class can have a numeric value, or whatever other attributes you find convenient.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.