简体   繁体   中英

Is there a generic solution in Java for mutual exclusion between threads based on a generated key?

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:

  • I could make the method synchronized, but it is an unneccessary bottleneck, since FooClass with id 1 and FooClass with id 2 can run parallel without problem.
  • I could generate a string with the id and make an intern() of it, and I could synchronize on that (I don't like this idea)
  • Synchronizing on Longs is also not a good idea.
  • I could create a 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:

  • There could be a LockManager or whatever, which is generized with a type (in my fall with Long above). It could provide a runSafely(Runnable run) method, which would do the mutual exclusion encapsulated, including generating the monitor object if needed, and removing it after. Of course I have to get the id inside this runSafely as well.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM