We can avoid the OptimisticCollisionException
by using the pessimistic lock strategy. The pessimistic strategy assumes that objects can and will be updated simultaneously by multiple threads. By assuming that multiple threads will be writing to objects in a BackingMap, we give up a little concurrency, but we don't need to handle OptimisticCollisionExceptions
. Where the optimistic lock strategy only briefly holds S or X locks, the pessimistic strategy holds locks for the duration of the transaction. The pessimistic lock strategy also makes the U lock available for use.
When we use a get
method to retrieve an object from a BackingMap, our transaction in thread 1 obtains an S lock on that object and holds it for the duration of the transaction. When thread 2 uses a get
method to retrieve the same object, the S lock held by thread 1 will not block thread 2 from obtaining an S lock. Now that both threads have S locks, they modify the state of the object and use a put
method to push...