3

I am interested to trigger a full memory fence without using sun.misc.Unsafe.

Does the following Java code trigger a full memory fence?

public final class Foo {
    public void bar() {
        // Before memory fence?
        synchronized(this) {
            // After memory fence?
        }
    }
}

Does the following Java code also trigger a full memory fence?

public final class Foo {
    private final Object monitor = new Object();
    public void bar() {
        // Before memory fence?
        synchronized(monitor) {
            // After memory fence?
        }
    }
}
Community
  • 1
  • 1
kevinarpe
  • 20,319
  • 26
  • 127
  • 154

2 Answers2

1

If you want to trigger a full fence manually, you need to have a look at the VarHandle. It has various fences.

Relying on synchronized blocks or volatiles purely for fencing behavior is very unreliable.

For example:

int a=0

thread1:
   a=1
   synchronized(this){}

thread2:
   synchronized(this){}
   r1=a

There is a data race on 'a' because 'a=1' could be read after the thread1 has updated a=1 and before it has released the lock. So there is no synchronizes-with edge that connects the write of a with the read of 1.

The JVM is free to produce a subset of all possible and valid executions and it could choose to only produce executions whereby 'a' remains zero and the new value will never be seen (since there is a data race). So the whole fence isn't taken into consideration.

pveentjer
  • 10,545
  • 3
  • 23
  • 40
0

What are you trying to achieve. Are you simply trying to prevent reordering of your "before" and "after" operations? Do you need your operations to be atomic?

To answer the question, Yes, locking will have the same effect of a full memory fence and more. It will ensure that your Before and After operations are not re-ordered. It will also ensure that all your writes within the synchronized block are visible to other threads. Further, all your operations done while holding the lock will happen atomically. Something that just adding a full fence wouldn't have accomplished.

Other way to trigger a full fence in java is to write to a volatile variable.

CaptainHastings
  • 1,557
  • 1
  • 15
  • 32