In a recent answer I suggested that it is possible to achieve the functionality of volatile
by synchronizing
on the object containing the variable we need to be volatile
(asker does not have access to the variable in code).
This got me thinking that I actually don't need to block on the containing object, I just need to achieve a memory barrier. As synchronized
achieves both synchronisation and a memory barrier, if all I need is the memory barrier (as in this case) would it actually be better to use synchronized(new Object())
to achieve my memory barrier and ensure the lock is never contended?