JavaMemoryModel: Immutable objects which aren't immutable

From: Miles Sabin (msabin@cromwellmedia.co.uk)
Date: Tue Apr 25 2000 - 06:26:24 EDT


I'm not sure that this is really an issue for this list or if
it's already been raised ... my apologies if it isn't or it
has.

java.util.Collections provides a family of methods for creating
immutable wrappers around the standard collection classes.
One might expect that instances of these could be safely shared.
Unfortunately that's not always the case, because at least
some of them use unsafe lazy initialization. In particular, the
definition of UnmodifiableMap.values() looks like this,

  private final Map m;
  private transient Collection values = null;

  public Collection values()
  {
    if(values == null)
      values = unmodifiableCollection(m.values());
    return values;
  }

Note that this isn't even minimally thread safe (hence my
being unsure if it's really an issue for this list), however
under various incorrect assumptions about the JMM the
initialization race here might appear relatively harmless ...
the only cost would be possible multiple initialization of the
private values field. Clearly, tho', that's not the worst that
could happen.

My real concern is that many reasonably clued up programmers
will assume that immutabilty is a general solution to
synchronization problems, and be tempted to use these wrapper
classes in unsafe ways. Maybe a future JMM JSR should address
these cases as well, even if only to the extent of recommending
that potential problems be flagged up in the relevant javadoc.

Cheers,

Miles

-- 
Miles Sabin                       Cromwell Media
Internet Systems Architect        5/6 Glenthorne Mews
+44 (0)20 8817 4030               London, W6 0LJ, England
msabin@cromwellmedia.com          http://www.cromwellmedia.com/

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



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