8200131: Improve lazy init of InetAddress.canonicalHostName and NativeObject.pageSize
authormartin
Thu, 05 Apr 2018 09:37:19 -0700
changeset 49531 e8ada9b2dd89
parent 49530 8f2ceebdc673
child 49532 745ce8f5efc8
8200131: Improve lazy init of InetAddress.canonicalHostName and NativeObject.pageSize Reviewed-by: alanb
src/java.base/share/classes/java/net/InetAddress.java
src/java.base/share/classes/sun/nio/ch/NativeObject.java
--- a/src/java.base/share/classes/java/net/InetAddress.java	Thu Apr 05 09:36:01 2018 -0700
+++ b/src/java.base/share/classes/java/net/InetAddress.java	Thu Apr 05 09:37:19 2018 -0700
@@ -290,7 +290,10 @@
     /* Used to store the name service provider */
     private static transient NameService nameService = null;
 
-    /* Used to store the best available hostname */
+    /**
+     * Used to store the best available hostname.
+     * Lazily initialized via a data race; safe because Strings are immutable.
+     */
     private transient String canonicalHostName = null;
 
     /** use serialVersionUID from JDK 1.0.2 for interoperability */
@@ -622,11 +625,11 @@
      * @since 1.4
      */
     public String getCanonicalHostName() {
-        if (canonicalHostName == null) {
-            canonicalHostName =
+        String value = canonicalHostName;
+        if (value == null)
+            canonicalHostName = value =
                 InetAddress.getHostFromNameService(this, true);
-        }
-        return canonicalHostName;
+        return value;
     }
 
     /**
--- a/src/java.base/share/classes/sun/nio/ch/NativeObject.java	Thu Apr 05 09:36:01 2018 -0700
+++ b/src/java.base/share/classes/sun/nio/ch/NativeObject.java	Thu Apr 05 09:37:19 2018 -0700
@@ -388,7 +388,10 @@
         return byteOrder;
     }
 
-    // Cache for page size
+    /**
+     * Cache for page size.
+     * Lazily initialized via a data race; safe because ints are atomic.
+     */
     private static int pageSize = -1;
 
     /**
@@ -397,9 +400,10 @@
      * @return  The page size, in bytes
      */
     static int pageSize() {
-        if (pageSize == -1)
-            pageSize = unsafe.pageSize();
-        return pageSize;
+        int value = pageSize;
+        if (value == -1)
+            pageSize = value = unsafe.pageSize();
+        return value;
     }
 
 }