Using Guava, I would like to have a map that has the following properties:
- A lot of reads, but very few writes.
- the data doesn’t expire.
- must be synchronized, so a write is “atomic” and multiple reads don’t interfere with each other.
- the map should use the
MapConstraintAPI and a few of theseMapConstraintare against the content of the map itself (typically if the records or another exists, do not overwrite it: throw anIllegalStateExceptioninstead). I see that theMapConstraintinterface doesn’t give theMapbeing constrained. - the
MapConstraint‘s check must be done inside the synchronization part.
I’ve well thought about using a ReadWriteLock, but I’m wondering if the MapMaker can help me here since I’m not very familiar with that API.
So what are my options?
Edit: My goal is not a simple putIfAbsent: I need to perform several checks against the map before inserting the value, always in the synchronized write.
I’m not sure if you can do this easily with the MapConstraint semantics. You could make the MapConstraint aware of the underlying map, by passing it a reference to the map during construction:
But it would be ugly / risky. Somebody could erroneously do:
Plus, it wouldn’t solve the synchronization problem.
If I were to do this, I would use the “putIfAbsent” method provided by ConcurrentMap. I would create a ConcurrentMap wrapper using ForwardingConcurrentMap: