JavaMemoryModel: String literals and String.intern()

From: Doron Rajwan (
Date: Fri Apr 16 2004 - 15:19:02 EDT

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


Initially a = 0.

Thread 1, Thread 2:
    synchronized ("some string") {

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

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

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

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


Doron Rajwan,

JavaMemoryModel mailing list -

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