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
  • 19,075
  • 22
  • 119
  • 144

1 Answers1

1

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,515
  • 1
  • 15
  • 28