changeset 10899:d06276cd8a40

8192056: Memory leak when removing javafx.scene.shape.Sphere-objects from a group or container Reviewed-by: kcr, nlisker
author arapte
date Fri, 13 Apr 2018 14:02:01 +0530
parents 996de9079c43
children f7643f961ac6
files modules/javafx.graphics/src/main/java/javafx/scene/shape/PredefinedMeshManager.java tests/system/src/test/java/test/javafx/scene/shape/meshmanagercacheleaktest/Constants.java tests/system/src/test/java/test/javafx/scene/shape/meshmanagercacheleaktest/MeshManagerCacheLeakApp.java tests/system/src/test/java/test/javafx/scene/shape/meshmanagercacheleaktest/MeshManagerCacheLeakTest.java
diffstat 4 files changed, 443 insertions(+), 36 deletions(-) [+]
line wrap: on
line diff
--- a/modules/javafx.graphics/src/main/java/javafx/scene/shape/PredefinedMeshManager.java	Fri Apr 13 12:16:12 2018 +0530
+++ b/modules/javafx.graphics/src/main/java/javafx/scene/shape/PredefinedMeshManager.java	Fri Apr 13 14:02:01 2018 +0530
@@ -27,18 +27,66 @@
 
 import java.util.HashMap;
 import java.util.Map;
-
+import java.lang.ref.SoftReference;
 import javafx.scene.shape.Shape3D.Key;
 
 final class PredefinedMeshManager {
-
-    private static final PredefinedMeshManager INSTANCE = new PredefinedMeshManager();
     private static final int INITAL_CAPACITY = 17; // TODO
     private static final float LOAD_FACTOR = 0.75f;
 
-    private Map<Key, TriangleMesh> boxCache = null;
-    private Map<Key, TriangleMesh> sphereCache = null;
-    private Map<Key, TriangleMesh> cylinderCache = null;
+    private static class TriangleMeshCache {
+        Map<Key, SoftReference<TriangleMesh>> cache = new HashMap<>(INITAL_CAPACITY, LOAD_FACTOR);
+
+        private TriangleMesh get(Key key) {
+            cleanCache();
+            return (cache.containsKey(key))? cache.get(key).get() : null;
+        }
+
+        private void put(Key key, TriangleMesh mesh) {
+            cleanCache();
+            if (mesh != null) {
+                cache.put(key, new SoftReference<TriangleMesh>(mesh));
+            }
+        }
+
+        private void cleanCache() {
+            cache.values().removeIf(ref -> ref.get() == null);
+        }
+
+        private void clear() {
+            cache.clear();
+        }
+
+        private int size() {
+            cleanCache();
+            return cache.size();
+        }
+
+        // for testing purpose
+        private void printStats(String name) {
+            System.out.println(name + " size:    " + size());
+        }
+
+        private void invalidateMesh(Key key) {
+            if (cache.containsKey(key)) {
+                TriangleMesh mesh = cache.get(key).get();
+                if (mesh != null) {
+                    mesh.decRef();
+                    int count = mesh.getRefCount();
+                    if (count == 0) {
+                        cache.remove(key);
+                    }
+                } else {
+                    cache.remove(key);
+                }
+            }
+        }
+    }
+
+    private static final PredefinedMeshManager INSTANCE = new PredefinedMeshManager();
+    private TriangleMeshCache boxCache = null;
+    private TriangleMeshCache sphereCache = null;
+    private TriangleMeshCache cylinderCache = null;
 
     private PredefinedMeshManager() {}
 
@@ -93,40 +141,19 @@
 
     synchronized void invalidateBoxMesh(Key key) {
         if (boxCache != null) {
-            TriangleMesh mesh = boxCache.get(key);
-            if (mesh != null) {
-                mesh.decRef();
-                int count = mesh.getRefCount();
-                if (count == 0) {
-                    boxCache.remove(key);
-                }
-            }
+            boxCache.invalidateMesh(key);
         }
     }
 
     synchronized void invalidateSphereMesh(Key key) {
         if (sphereCache != null) {
-            TriangleMesh mesh = sphereCache.get(key);
-            if (mesh != null) {
-                mesh.decRef();
-                int count = mesh.getRefCount();
-                if (count == 0) {
-                    sphereCache.remove(key);
-                }
-            }
+            sphereCache.invalidateMesh(key);
         }
     }
 
     synchronized void invalidateCylinderMesh(Key key) {
         if (cylinderCache != null) {
-            TriangleMesh mesh = cylinderCache.get(key);
-            if (mesh != null) {
-                mesh.decRef();
-                int count = mesh.getRefCount();
-                if (count == 0) {
-                    cylinderCache.remove(key);
-                }
-            }
+            cylinderCache.invalidateMesh(key);
         }
     }
 
@@ -146,15 +173,15 @@
     // for testing purpose
     synchronized void printStats() {
         if (boxCache != null) {
-            System.out.println("BoxCache size:  " +  boxCache.size());
+            boxCache.printStats("BoxCache");
         }
 
         if (sphereCache != null) {
-            System.out.println("SphereCache size:    " + sphereCache.size());
+            sphereCache.printStats("SphereCache");
         }
 
         if (cylinderCache != null) {
-            System.out.println("CylinderCache size:    " + cylinderCache.size());
+            cylinderCache.printStats("CylinderCache");
         }
     }
 
@@ -189,19 +216,19 @@
     private final static class BoxCacheLoader {
 
         // lazy & thread-safe instantiation
-        private static final Map<Key, TriangleMesh> INSTANCE = new HashMap<>(INITAL_CAPACITY, LOAD_FACTOR);
+        private static final TriangleMeshCache INSTANCE = new TriangleMeshCache();
     }
 
     private final static class SphereCacheLoader {
 
         // lazy & thread-safe instantiation
-        private static final Map<Key, TriangleMesh> INSTANCE = new HashMap<>(INITAL_CAPACITY, LOAD_FACTOR);
+        private static final TriangleMeshCache INSTANCE = new TriangleMeshCache();
     }
 
     private final static class CylinderCacheLoader {
 
         // lazy & thread-safe instantiation
-        private static final Map<Key, TriangleMesh> INSTANCE = new HashMap<>(INITAL_CAPACITY, LOAD_FACTOR);
+        private static final TriangleMeshCache INSTANCE = new TriangleMeshCache();
     }
 
 };
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/tests/system/src/test/java/test/javafx/scene/shape/meshmanagercacheleaktest/Constants.java	Fri Apr 13 14:02:01 2018 +0530
@@ -0,0 +1,41 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package test.javafx.scene.shape.meshmanagercacheleaktest;
+
+public class Constants {
+    // Error exit codes. Note that 0 and 1 are reserved for normal exit and
+    // failure to launch java, respectively
+    public static final int ERROR_NONE = 2;
+    public static final int ERROR_SOCKET = 3;
+    public static final int ERROR_OOM = 4;
+    public static final int ERROR_LAUNCH = 5;
+
+    // Socket handshake value used at initialization (8-bit value)
+    public static final int SOCKET_HANDSHAKE = 126;
+
+    public static final int STATUS_OK = 1;
+    public static final int STATUS_OOM = 2;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/tests/system/src/test/java/test/javafx/scene/shape/meshmanagercacheleaktest/MeshManagerCacheLeakApp.java	Fri Apr 13 14:02:01 2018 +0530
@@ -0,0 +1,206 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package test.javafx.scene.shape.meshmanagercacheleaktest;
+
+import javafx.application.Application;
+import javafx.application.Platform;
+import javafx.scene.Group;
+import javafx.scene.Scene;
+import javafx.stage.Stage;
+import javafx.stage.WindowEvent;
+import javafx.scene.layout.HBox;
+import javafx.scene.shape.Box;
+import javafx.scene.shape.Cylinder;
+import javafx.scene.shape.Shape3D;
+import javafx.scene.shape.Sphere;
+import java.util.concurrent.TimeUnit;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.net.Socket;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.CountDownLatch;
+
+import static test.javafx.scene.shape.meshmanagercacheleaktest.Constants.*;
+
+/*
+ * Test application launched by MeshManagerCacheLeakTest with -Xmx16m.
+ * Test steps:
+ * 1. Create scene with a container.
+ * 2. Reserve maximum memory of available memory.
+ * 3. Add and remove different sized shapes to scene.
+ * 4. Verify that, no OOM occurs.
+ */
+public class MeshManagerCacheLeakApp {
+
+    // Socket for communicating with MeshManagerCacheLeakTest
+    private static Socket socket;
+    private static OutputStream out;
+    private static boolean statusWritten = false;
+
+    static String shapeType;
+    static int numShapes = 0;
+    CountDownLatch latch;
+    static CountDownLatch startupLatch = new CountDownLatch(1);
+    static Group container;
+    static volatile Stage stage;
+
+    public static class TestApp extends Application {
+        @Override
+        public void start(Stage pStage) {
+            // 1. Create scene with a container.
+            stage = pStage;
+            HBox root = new HBox();
+            container = new Group();
+            root.getChildren().add(container);
+            Scene scene = new Scene(root);
+            stage.setScene(scene);
+            stage.addEventHandler(WindowEvent.WINDOW_SHOWN, e ->
+                    Platform.runLater(startupLatch::countDown));
+            stage.show();
+        }
+    }
+
+    private static void initSocket(String[] args) throws Exception {
+        int port = Integer.parseInt(args[0]);
+        socket = new Socket((String)null, port);
+        out = socket.getOutputStream();
+        out.write(SOCKET_HANDSHAKE);
+        out.flush();
+    }
+
+    private synchronized static void writeStatus(int status) {
+        if (!statusWritten) {
+            statusWritten = true;
+            try {
+                out.write(status);
+                out.flush();
+            } catch (IOException ex) {
+                ex.printStackTrace(System.err);
+            }
+        }
+    }
+
+    public void testOOM() {
+        System.gc();
+        System.runFinalization();
+
+        AtomicInteger err = new AtomicInteger(STATUS_OOM);
+        try {
+            // 2. Reserve maximum of available memory.
+            byte[] mem = null;
+            if (shapeType.equals("Sphere")) {
+                mem = new byte[1024 * 1024 * 8];
+            } else if (shapeType.equals("Cylinder")) {
+                mem = new byte[1024 * 1024 * 8];
+            } else if (shapeType.equals("Box")) {
+                mem = new byte[1024 * 1024 * 11];
+            }
+            float radius = 20.0f;
+            float height = 20;
+            int sphereDivisions = 70;
+            int cylinderDivisions = 512;
+            int boxWHD = 300;
+
+            for (int i = 0; i < numShapes; ++i) {
+                // 3. Add and remove different sized shapes to scene.
+                Shape3D shape = null;
+                if (shapeType.equals("Sphere")) {
+                    shape = new Sphere(radius++, sphereDivisions);
+                } else if (shapeType.equals("Cylinder")) {
+                    shape = new Cylinder(radius++, height, cylinderDivisions);
+                } else if (shapeType.equals("Box")) {
+                    shape = new Box(boxWHD++, boxWHD, boxWHD);
+                }
+
+                latch = new CountDownLatch(1);
+                Shape3D shp = shape;
+                Platform.runLater(() -> {
+                    try {
+                        container.getChildren().add(shp);
+                        latch.countDown();
+                    } catch (OutOfMemoryError e) {
+                        writeStatus(err.get());
+                        System.exit(0);
+                    } catch (Exception e) {
+                        writeStatus(err.get());
+                        System.exit(0);
+                    }
+                });
+                waitForLatch(latch, 5, -1);
+
+                // The TriangleMesh for the added shape
+                // is created on next pulse, hence the sleep
+                // for approximately 2 pulse duration.
+                Thread.sleep(35); // ~((1000 / 60) * 2)
+
+                latch = new CountDownLatch(1);
+                Platform.runLater(() -> {
+                    container.getChildren().clear();
+                    latch.countDown();
+                });
+                waitForLatch(latch, 5, -1);
+            }
+        } catch (OutOfMemoryError e) {
+            writeStatus(err.get());
+            System.exit(0);
+        } catch (Exception e) {
+            writeStatus(err.get());
+            System.exit(0);
+        }
+
+        // 4. Verify that, no OOM occurs.
+        err.set(STATUS_OK);
+        writeStatus(err.get());
+        System.exit(ERROR_NONE);
+    }
+
+    public void waitForLatch(CountDownLatch cdLatch, int seconds, int error) {
+        try {
+            if (!cdLatch.await(seconds, TimeUnit.SECONDS)) {
+                System.exit(error);
+            }
+        } catch (Exception ex) {
+            System.exit(error);
+        }
+    }
+
+    public static void main(String[] args) {
+        try {
+            initSocket(args);
+        } catch (Exception ex) {
+            ex.printStackTrace(System.err);
+            System.exit(ERROR_SOCKET);
+        }
+        shapeType = args[1];
+        numShapes = Integer.parseInt(args[2]);
+
+        MeshManagerCacheLeakApp test = new MeshManagerCacheLeakApp();
+        new Thread(() -> Application.launch(TestApp.class, (String[])null)).start();
+        test.waitForLatch(startupLatch, 10, ERROR_LAUNCH);
+        test.testOOM();
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/tests/system/src/test/java/test/javafx/scene/shape/meshmanagercacheleaktest/MeshManagerCacheLeakTest.java	Fri Apr 13 14:02:01 2018 +0530
@@ -0,0 +1,133 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package test.javafx.scene.shape.meshmanagercacheleaktest;
+
+import java.io.InputStream;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.util.ArrayList;
+
+import javafx.application.ConditionalFeature;
+import javafx.application.Platform;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.Assert;
+import static org.junit.Assert.fail;
+import static org.junit.Assume.assumeTrue;
+
+import static test.javafx.scene.shape.meshmanagercacheleaktest.Constants.*;
+
+/**
+ * Unit test for verifying leak with cache of TriangleMesh in PredefinedMeshManager.
+ */
+public class MeshManagerCacheLeakTest {
+
+    private static final String className = MeshManagerCacheLeakTest.class.getName();
+    private static final String pkgName = className.substring(0, className.lastIndexOf("."));
+    private final String testAppName = pkgName + "." + "MeshManagerCacheLeakApp";
+
+    @Before
+    public void setUp() {
+        assumeTrue(Platform.isSupported(ConditionalFeature.SCENE3D));
+    }
+
+    @Test
+    public void testMeshManagerCacheLeak() throws Exception {
+        // Initilaize the socket
+        final ServerSocket service = new ServerSocket(0);
+        final int port = service.getLocalPort();
+        String[] jvmArgs = {"-Xmx16m"};
+        String[] testArgs = { "Sphere", "Cylinder", "Box"};
+        String[] numShapes = { "10", "25", "350"};
+
+        for (int i = 0; i < testArgs.length; ++i) {
+            // Launch the test app
+            final ArrayList<String> cmd
+                    = test.util.Util.createApplicationLaunchCommand(testAppName,
+                            null, null, jvmArgs);
+            // and add our arguments
+            cmd.add(String.valueOf(port));
+            cmd.add(String.valueOf(testArgs[i]));
+            cmd.add(String.valueOf(numShapes[i]));
+            ProcessBuilder builder = new ProcessBuilder(cmd);
+            builder.redirectError(ProcessBuilder.Redirect.INHERIT);
+            builder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
+            Process process = builder.start();
+
+            // Accept a connection from the test app
+            final Socket socket = service.accept();
+            final InputStream in = socket.getInputStream();
+
+            // Read the "handshake" token
+            int handshake = in.read();
+            Assert.assertEquals("Socket handshake failed,", SOCKET_HANDSHAKE, handshake);
+
+            // Read the status code from the test app.
+            int status = in.read();
+            switch (status) {
+                case STATUS_OK:
+                    break;
+                case STATUS_OOM:
+                    fail(testAppName
+                        + ": OOM occured with cache of : " + testArgs[i]);
+                    break;
+                default:
+                    fail(testAppName + ": Unexpected status: " + status + " with cache of : " + testArgs[i]);
+            }
+
+            // Make sure that the process exited as expected
+            int retVal = process.waitFor();
+            switch (retVal) {
+                case ERROR_NONE:
+                    break;
+
+                case 0:
+                    fail(testAppName + ": Unexpected exit 0 with cache test of : " + testArgs[i]);
+                    break;
+
+                case 1:
+                    fail(testAppName + ": Unable to launch java application with cache test of : " + testArgs[i]);
+                    break;
+
+                case ERROR_SOCKET:
+                    fail(testAppName + ": Error connecting to socket with cache test of : " + testArgs[i]);
+                    break;
+
+                case ERROR_OOM:
+                    fail(testAppName + ": OOM occured with cache test of : " + testArgs[i]);
+                    break;
+
+                case ERROR_LAUNCH:
+                    fail(testAppName + ": Window was not shown for more than 10 secs, with cache test of : " + testArgs[i]);
+                    break;
+
+                default:
+                    fail(testAppName + ": Unexpected error exit: " + retVal + " with cache test of : " + testArgs[i]);
+            }
+        }
+    }
+}