1 /*
   2  * Copyright (c) 2010, 2016, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  */
  23 
  24 import java.io.BufferedReader;
  25 import java.io.InputStream;
  26 import java.io.InputStreamReader;
  27 
  28 import static jdk.testlibrary.Asserts.assertGreaterThan;
  29 import jdk.test.lib.process.ProcessTools;
  30 
  31 import com.sun.tools.attach.AttachNotSupportedException;
  32 import com.sun.tools.attach.VirtualMachine;
  33 
  34 import sun.tools.attach.HotSpotVirtualMachine;
  35 
  36 /*
  37  * @test
  38  * @bug 6942989
  39  * @summary Check for WeakReference leak in Logger and anonymous Logger objects
  40  * @library /lib/testlibrary
  41  * @library /test/lib
  42  * @modules jdk.attach/sun.tools.attach
  43  *          java.logging
  44  * @build jdk.test.lib.process.ProcessTools
  45  * @run main/othervm -Djdk.attach.allowAttachSelf TestLoggerWeakRefLeak Logger
  46  * @run main/othervm -Djdk.attach.allowAttachSelf TestLoggerWeakRefLeak AnonymousLogger
  47  */
  48 public class TestLoggerWeakRefLeak {
  49 
  50     private static final String TARGET_CLASS = "java.lang.ref.WeakReference";
  51     private static final int INSTANCE_COUNT = 100;
  52     private static int loggerCount = 0;
  53 
  54     public static void main(String[] args) throws Exception {
  55         if (args[0].equals("AnonymousLogger")) {
  56             System.out.println("Test for WeakReference leak in AnonymousLogger object");
  57             testIfLeaking(TestLoggerWeakRefLeak::callAnonymousLogger);
  58         } else {
  59             System.out.println("Test for WeakReference leak in Logger object");
  60             testIfLeaking(TestLoggerWeakRefLeak::callLogger);
  61         }
  62     }
  63 
  64     /**
  65      * For these particular WeakReference leaks, the count was always observed
  66      * to be increasing so if decreasing or the same count is observed,
  67      * then there is no leak.
  68      */
  69     private static void testIfLeaking(Runnable callLogger) throws Exception {
  70         long count = 0;
  71         int instanceCount = 0;
  72         int previousInstanceCount = 0;
  73         int increasingCount = 0;
  74         int decreasingCount = 0;
  75 
  76         while (true) {
  77             callLogger.run();
  78             count += INSTANCE_COUNT;
  79 
  80             if ((count % 1000) == 0) {
  81                 System.out.println("call count = " + count);
  82 
  83                 instanceCount = getInstanceCountFromHeapHisto();
  84                 if (instanceCount > previousInstanceCount) {
  85                     increasingCount++;
  86                 } else {
  87                     decreasingCount++;
  88                     System.out.println("increasing count: " + increasingCount);
  89                     System.out.println("decreasing or the same count: " + decreasingCount);
  90                     System.out.println("Test passed: decreasing or the same instance count is observed");
  91                     break;
  92                 }
  93                 previousInstanceCount = instanceCount;
  94             }
  95 
  96             delayExecution();
  97         }
  98     }
  99 
 100     /**
 101      * This Logger call is leaking two different WeakReferences:
 102      * - one in LogManager.LogNode
 103      * - one in Logger.kids
 104      */
 105     private static void callLogger() {
 106         for (int i = 0; i < INSTANCE_COUNT; i++) {
 107             java.util.logging.Logger.getLogger("logger-" + loggerCount);
 108             if (++loggerCount >= 25000) {
 109                 // Limit the Logger namespace used by the test so the weak refs
 110                 // in LogManager.loggers that are being properly managed
 111                 // don't skew the counts by too much.
 112                 loggerCount = 0;
 113             }
 114         }
 115     }
 116 
 117     /**
 118      * This Logger call is leaking a WeakReference in Logger.kids
 119      */
 120     private static void callAnonymousLogger() {
 121         for (int i = 0; i < INSTANCE_COUNT; i++) {
 122             java.util.logging.Logger.getAnonymousLogger();
 123         }
 124     }
 125 
 126     /**
 127      * 'vm.heapHisto("-live")' will request a full GC
 128      */
 129     private static int getInstanceCountFromHeapHisto() throws AttachNotSupportedException, Exception {
 130         int instanceCount = 0;
 131 
 132         HotSpotVirtualMachine vm = (HotSpotVirtualMachine) VirtualMachine
 133                 .attach(Long.toString(ProcessTools.getProcessId()));
 134         try {
 135             try (InputStream heapHistoStream = vm.heapHisto("-live");
 136                     BufferedReader in = new BufferedReader(new InputStreamReader(heapHistoStream))) {
 137                 String inputLine;
 138                 while ((inputLine = in.readLine()) != null) {
 139                     if (inputLine.contains(TARGET_CLASS)) {
 140                         instanceCount = Integer.parseInt(inputLine
 141                                 .split("[ ]+")[2]);
 142                         System.out.println("instance count: " + instanceCount);
 143                         break;
 144                     }
 145                 }
 146             }
 147         } finally {
 148             vm.detach();
 149         }
 150 
 151         assertGreaterThan(instanceCount, 0, "No instances of " + TARGET_CLASS + " are found");
 152 
 153         return instanceCount;
 154     }
 155 
 156     /**
 157      * Delay for 1/10 of a second to avoid CPU saturation
 158      */
 159     private static void delayExecution() {
 160         try {
 161             Thread.sleep(100);
 162         } catch (InterruptedException ie) {
 163             // Ignore any exceptions
 164         }
 165     }
 166 
 167 }