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?
A Synchronized block is a piece of code that can be used to perform synchronization on any specific resource of the method. A Synchronized block is used to lock an object for any shared resource and the scope of a synchronized block is smaller than the synchronized method.
Synchronized methods enable a simple strategy for preventing thread interference and memory consistency errors: if an object is visible to more than one thread, all reads or writes to that object's variables are done through synchronized methods.
Synchronized blocks in Java are marked with the synchronized keyword. A synchronized block in Java is synchronized on some object. All synchronized blocks synchronize on the same object can only have one thread executing inside them at a time.
When a thread invokes a synchronized method, it automatically acquires the intrinsic lock for that method's object and releases it when the method returns. The lock release occurs even if the return was caused by an uncaught exception.
As explained here: http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html#synchronization synchronized(new Object()) is considered a noop and may be removed entirely by the compiler. You won't get a memory barrier out of it.
In addition to @assylias's very good point, also consider that synchronized
does not achieve a memory barrier by specification. It is only the case that this is how it is implemented on today's typical CPU-memory architectures. The specification only guarantees what happens when two threads acquire the same lock.
Anyway, if you don't care about the specification, but only about the real-world implementations, then why not introduce your own volatile
variable and simply write to it whenever you want a memory barrier? It is irrelevant which volatile
you write to, as long as we're talking about a constrained set of architectures which is implied by your synchronized(new Object())
idea.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With