Empty synchronized blocks can usually not be eliminated, independent of
the memory model details. For example,
they can be used to delay a new child thread until the parent thread
passes a certain point by having the parent hold a lock during
thread creation, and having the child briefly acquire the lock.
Not that this is the right way to do things in Java, but it does
sometimes make sense for pthreads.
I believe your example does guarantee that zero can't be printed.
(Declaring "global" to be volatile would have been both cheaper and
more transparent.)
Hans
> -----Original Message-----
> From: owner-javamemorymodel@cs.umd.edu
> [mailto:owner-javamemorymodel@cs.umd.edu]On Behalf Of Doron Rajwan
> Sent: Wednesday, April 14, 2004 8:43 AM
> To: javamemorymodel@cs.umd.edu
> Subject: JavaMemoryModel: Empty synchronized blocks are not
> useless (?)
>
>
>
> 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?
>
> Doron.
>
>
> =====
> Doron Rajwan, mailto:doron@rajwan.org
>
> -------------------------------
> JavaMemoryModel mailing list -
http://www.cs.umd.edu/~pugh/java/memoryModel
-------------------------------
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