iammat
iammat

Reputation: 61

Synchronizing based on contents of Map

I want to synchronize a block of code, but do not want to simply lock on the implementing class (this).

The block of code in question is part of a method which takes in an id.

I want to disallow a new thread from entering the block if the id passed into the method is contained within a list in the class... if it not in the list, the entity is free to operate on, and thus the thread will be allowed into the block...

Is there a straight forward way to do this?

Upvotes: 2

Views: 79

Answers (1)

Kayaman
Kayaman

Reputation: 73538

There is no explicit class for this in the JDK, but as described in the (previous) duplicate, you can use ConcurrentHashMap to implement this kind of behaviour.

Guava provides the Striped class that gives you a good solution with plenty of configuration, such as lazily creating locks and weak locks, as well as configuring the amount of stripes (locks) to be used.

Upvotes: 5

Related Questions