[jmm-dev] bitwise RMW operators, specifically testAndSetBit/BTS

Martin Buchholz martinrb at google.com
Fri Jul 15 21:39:53 UTC 2016

On Thu, Jul 14, 2016 at 7:09 PM, John Rose <john.r.rose at oracle.com> wrote:

> The particular use case I have in mind is SeqLocks, specifically the
> writer-enter operation, which needs to change the lock state to "odd",
> unless it is already "odd", and let the processor know what happened.  An
> "xadd" cannot do this, but a "cmpxchg" or "bts" can, and the "bts" is
> preferable.

Most synchronizers have more complex state than "locked or unlocked".
StampedLock is a read-write lock, so you can only acquire the write lock if
not currently read-locked.  (Did I miss something?) ReentrantLock is
reentrant (!) so needs to store the lock hold count.  Perhaps ReentrantLock
could benefit if you optimize for non-reentrant acquires, at the cost of
doing an extra update for reentrant acquires.

(In a rather deep sense, getAndAdd is less powerful than testAndSetBit or
> getAndBitwiseOr,
> because op+ is bijective in each argument, while op| is idempotent.  This
> means that
> you can operate bitwise on a structure in such a way that your operation
> disappears
> when the structure is already in some state you are pushing it towards.
> Of course,
> you also need a way to "exchange" in the previous value, atomically.)

More information about the jmm-dev mailing list