Re: JavaMemoryModel: init methods

From: Doug Lea (dl@cs.oswego.edu)
Date: Tue Sep 26 2000 - 08:10:55 EDT


> If I understand correctly, some of the proposed fixes to JMM are
> designed so that immutable objects can be accessed without
> synchronization once they are constructed.
>
> Q1: These guarantees don't address bean-style construction (akin to
> factory-style construction), right?
>
> For example, given:
>
> Bean bean = new Bean();
> bean.setFoo(fooValue);
> bean.setBar(barValue);
> return bean;
>
> If one thread initializes the bean and publishes it and another
> thread accesses the bean without synch., then the accessing thread may
> see an uninitialized bean.
>

Under current proposals, the best recourse here is for programmers to
declare any fields holding refs to beans constructed in such a manner
as volatile. This is not too horrible: I do not think there is any
plausible rule that will cause such code to work without modification,
and adding a "volatile" is probably the simplest possible modification
we could ask for.

It's still uncomfortable though that there is a lot of code out there
of this form that will surely remain broken -- with JavaBeans and
other frameworks, you are not allowed to declare write-once fields as
final since you must have a no-arg constructor, so there is no good
way for people to take advantage of rules for finals.

David Holmes has suggested that there be some way to mark such code
bodies to have essentially the effects of proposed rules for finals
and volatiles; for example as:

  volatile {
    Bean bean = new Bean();
    bean.setFoo(fooValue);
    bean.setBar(barValue);
    return bean;
  }

But this is messy, leads to other odd rules and side conditions, and
still doesn't automagically fix broken code. (The oddest/ugliest
aspects stem from non-local effects: all reader-methods associated
with a class with such a clause would need read-barriers on some
platforms.) But still maybe worth considering.

-- 
Doug Lea, Computer Science Department, SUNY Oswego, Oswego, NY 13126 USA
dl@cs.oswego.edu 315-341-2688 FAX:315-341-5424 http://gee.cs.oswego.edu/  
-------------------------------
JavaMemoryModel mailing list - http://www.cs.umd.edu/~pugh/java/memoryModel



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