Race condition in Class.getName()

Martin Buchholz martinrb at google.com
Thu Sep 10 00:35:10 UTC 2009


It is believed that the java memory model allows Class.getName()
to return null.
This is one of those methods with an intentional data race.
Probably this has not been seen in practice because only
a perverse or adversarial runtime would load the "name" field
twice, out-of-order, as it seems to be allowed to.

diff --git a/src/share/classes/java/lang/Class.java
b/src/share/classes/java/lang/Class.java
--- a/src/share/classes/java/lang/Class.java
+++ b/src/share/classes/java/lang/Class.java
@@ -565,8 +565,9 @@
      *          represented by this object.
      */
     public String getName() {
+        String name = this.name;
         if (name == null)
-            name = getName0();
+            this.name = name = getName0();
         return name;
     }

Martin



More information about the core-libs-dev mailing list