Usage example for synchronization (new Object ())

In a recent answer, I suggested that for an object containing this variable, volatile synchronizing volatile functionality can be achieved (asker does not have access to the variable in the code).

This made me think that in fact I do not need to block the contained object, I just need to reach the memory barrier. Since synchronized provides both a synchronization and a memory barrier, if all I need is a memory barrier (as in this case), it would be better to use synchronized(new Object()) to reach my memory barrier and make sure that the lock is never considered ?

+6
source share
3 answers

In addition to @assylias, a very good point, also keep in mind that synchronized does not reach the memory barrier by specification. The fact is that this is how it is implemented on today's typical CPU memory architectures. The specification only guarantees what happens when two threads receive the same lock.

In any case, if you do not care about the specification, but only about the realities of the real world, then why not introduce your own variable volatile and just write it whenever you need a memory barrier? It doesn't matter which volatile you write to, while we are talking about a limited set of architectures, which is implied by your idea of synchronized(new Object()) .

+2
source

As explained here: http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html#synchronization synchronized (new Object ()) is considered to be noop and can be completely removed by the compiler. From this, you will not get a memory barrier.

+3
source

would it be better to use synchronized(new Object()) to achieve my memory barrier and ensure blocking will never fight?

Nop. The JVM can easily prove that two threads cannot be accessible to this lock (since this is a local thread variable) and will almost certainly turn it into a no-op, that is, completely remove the synchronized statement.

+2
source

Source: https://habr.com/ru/post/945670/


All Articles