JavaMemoryModel: String literals and String.intern()

From: Eliot Moss (moss@cs.umass.edu)
Date: Fri Apr 16 2004 - 21:34:18 EDT


>>>>> "Doron" == Doron Rajwan <doron@rajwan.org> writes:

    Doron> The JLS specifies that all string literals within the
    Doron> code are interned, i.e., singleton instances that can
    Doron> be compared using ==. Moreover, String has intern()
    Doron> method, that returned an interned instance of the
    Doron> String.

    Doron> Example:

    Doron> Initially a = 0.

    Doron> Thread 1, Thread 2:
    Doron> synchronized ("some string") {
    Doron> ++a;
    Doron> }

    Doron> 1. This is a "critical section"; it is impossible that
    Doron> both threads will be inside it at once.

    Doron> 2. However, it is possible that the first thread
    Doron> finished, the GC collected the interned string, and
    Doron> then, the second thread started. In this case, the
    Doron> sync was on a different instance of the String.

Doron, I don't get what you're saying. Even a copying GC has to preserve
identity semantics in the face of locking objects. And so far as I know, an
interned string will never be reclaimed anyway.

    Doron> 3. Thus, it seems that w/o specific knowledge of how
    Doron> the interned strings are implemented, there can be a
    Doron> potential data race here (although extremely
    Doron> unlikely).

    Doron> 4. If a distributed JVM is to be implemented, these
    Doron> interned strings can be a pain. I would consider
    Doron> specifying in the JLS that interned strings may not be
    Doron> used to synchronize between threads. Otherwise, the
    Doron> JVM will have to synchronize each access to a string
    Doron> literal between all machines!

Well now here you have a point. One would prefer pure value semantics for
strings, but if someone synchronizes on one, then the distributed Java will
need to support this semantics. However, you end up with the same problem
when constructing any non-primitiive immutable type where you want identity
to be on the _value_, not the representing instance.

Regards -- Eliot Moss
==============================================================================
J. Eliot B. Moss, Associate Professor http://www.cs.umass.edu/~moss www
Director, Arch. and Lang. Impl. Lab. +1-413-545-4206 voice
Department of Computer Science +1-413-695-4226 cell
140 Governor's Drive, Room 372 +1-413-545-1249 fax
University of Massachusetts at Amherst moss@cs.umass.edu email
Amherst, MA 01003-9264 USA +1-413-545-3733 Priscilla Coe sec'y
==============================================================================
-------------------------------
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