Re: JavaMemoryModel: Empty synchronized blocks are not useless (?)

From: Bill Pugh (pugh@cs.umd.edu)
Date: Wed Apr 14 2004 - 14:53:07 EDT


On Apr 14, 2004, at 11:42 AM, Doron Rajwan wrote:

>
> As I understand the JMM, an empty synchronized block
> is not automatically uesless. For example, the test
> below is well-synchronized. Is this correct?
>
>
> class Obj {
> private static Object SOMETHING = new Object();
> private int x;
> public void setX(int x) {
> this.x = x;
> synchronized(SOMETHING) {}
> }
> public int getX() {
> synchronized(SOMETHING) {}
> return x;
> }
> }
>
>
> Initially, global = null.
>
> Thread 1:
> Obj obj = new Obj();
> obj.setX(3);
> global = obj;
>
> Thread 2:
> Obj obj = global;
> if (obj != null)
> System.out.println(obj.getX());
>
> Can this code print 0?

No, it can not print zero.

It is not correctly synchronized, since there is a data
race on global. But there is no data race on x.

In other uses of this class, there could be a race on x.

Consider:

Initially: global = new Obj();

Thread 1:
r1 = global.getX()

Thread 2:
global.setX(42)

You can have a data race on x. In particular,
Thread 1 acquires and releases the lock.
Thread 2 writes to x
thread 1 reads x
Thread 2 acquires and releases the lock

So you have threads 1 and 2 with conflicting accesses to x,
that are not ordered by happens-before.

        Bill

-------------------------------
JavaMemoryModel mailing list - http://www.cs.umd.edu/~pugh/java/memoryModel



This archive was generated by hypermail 2b29 : Thu Oct 13 2005 - 07:01:04 EDT