1 /*
   2  * Copyright (c) 2003, 2018, 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 /*
  25  * The -XX:MarkSweepAlwaysCompactCount=1 argument below makes sure serial gc
  26  * compacts the heap at every full gc so that the usage is correctly updated.
  27  */
  28 
  29 /*
  30  * @test
  31  * @bug     4892507
  32  * @summary Basic Test for MemoryPool.resetPeakUsage()
  33  * @author  Mandy Chung
  34  *
  35  * @requires vm.opt.ExplicitGCInvokesConcurrent != "true"
  36  * @requires vm.opt.DisableExplicitGC != "true"
  37  * @library /lib/testlibrary/ /test/lib
  38  * @modules jdk.management
  39  *
  40  * @build jdk.testlibrary.* ResetPeakMemoryUsage MemoryUtil RunUtil
  41  * @build sun.hotspot.WhiteBox
  42  * @run driver ClassFileInstaller sun.hotspot.WhiteBox sun.hotspot.WhiteBox$WhiteBoxPermission
  43  * @run main/othervm -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI -Xbootclasspath/a:. ResetPeakMemoryUsage
  44  */
  45 
  46 import java.lang.management.*;
  47 import java.lang.ref.WeakReference;
  48 import java.util.*;
  49 
  50 import sun.hotspot.code.Compiler;
  51 import sun.hotspot.WhiteBox;
  52 
  53 public class ResetPeakMemoryUsage {
  54     private static MemoryMXBean mbean = ManagementFactory.getMemoryMXBean();
  55     // make public so that it can't be optimized away easily
  56     public static Object[] obj;
  57 
  58     /**
  59      * Run the test multiple times with different GC versions.
  60      * First with default command line specified by the framework.
  61      * Then with all GC versions specified by the test.
  62      */
  63     public static void main(String a[]) throws Throwable {
  64         final String main = "ResetPeakMemoryUsage$TestMain";
  65         final String ms = "-Xms256m";
  66         final String mn = "-Xmn8m";
  67         if (!Compiler.isGraalEnabled()) { // Graal does not support CMS
  68             RunUtil.runTestClearGcOpts(main, ms, mn, "-XX:+UseConcMarkSweepGC");
  69         }
  70         RunUtil.runTestClearGcOpts(main, ms, mn, "-XX:+UseParallelGC");
  71         RunUtil.runTestClearGcOpts(main, ms, mn, "-XX:+UseG1GC", "-XX:-G1UseLegacyMonitoring",
  72                                    "-XX:G1HeapRegionSize=1m");
  73         RunUtil.runTestClearGcOpts(main, ms, mn, "-XX:+UseG1GC", "-XX:+G1UseLegacyMonitoring",
  74                                    "-XX:G1HeapRegionSize=1m");
  75         RunUtil.runTestClearGcOpts(main, ms, mn, "-XX:+UseSerialGC",
  76                                    "-XX:MarkSweepAlwaysCompactCount=1");
  77     }
  78 
  79     private static class TestMain {
  80         public static void main(String[] argv) {
  81             List pools = ManagementFactory.getMemoryPoolMXBeans();
  82             ListIterator iter = pools.listIterator();
  83             boolean found = false;
  84             while (iter.hasNext()) {
  85                 MemoryPoolMXBean p = (MemoryPoolMXBean) iter.next();
  86                 // Only check heap pools that support a usage threshold.
  87                 // This is typically only the old generation space
  88                 // since the other spaces are expected to get filled up.
  89                 if (p.getType() == MemoryType.HEAP &&
  90                     p.isUsageThresholdSupported()) {
  91                     // In all collectors except G1, only the old generation supports a
  92                     // usage threshold. The G1 legacy mode "G1 Old Gen" also does. In
  93                     // G1 default mode, both the old space ("G1 Old Space": it's not
  94                     // really a generation in the non-G1 collector sense) and the
  95                     // humongous space ("G1 Humongous Space"), support a usage threshold.
  96                     // So, the following condition is true for all non-G1 old generations,
  97                     // for the G1 legacy old gen, and for the G1 default humongous space.
  98                     // It is not true for the G1 default old gen.
  99                     //
 100                     // We're allocating humongous objects in this test, so the G1 default
 101                     // mode "G1 Old Space" occupancy doesn't change, because humongous
 102                     // objects are allocated in the "G1 Humongous Space". If we allowed
 103                     // the G1 default mode "G1 Old Space", notification would never
 104                     // happen because no objects are allocated there.
 105                     if (!p.getName().equals("G1 Old Space")) {
 106                         found = true;
 107                         testPool(p);
 108                     }
 109                 }
 110             }
 111             if (!found) {
 112                 throw new RuntimeException("No heap pool found");
 113             }
 114         }
 115     }
 116 
 117     private static void testPool(MemoryPoolMXBean mpool) {
 118         System.out.println("Selected memory pool: ");
 119         MemoryUtil.printMemoryPool(mpool);
 120 
 121         MemoryUsage usage0 = mpool.getUsage();
 122         MemoryUsage peak0 = mpool.getPeakUsage();
 123 
 124         // use a size that is larger than the young generation and G1 regions
 125         // to force the array into the old gen
 126         int largeArraySize = 9 * 1000 * 1000;
 127 
 128         System.out.println("Before big object array (of size "+largeArraySize+") is allocated: ");
 129         printMemoryUsage(usage0, peak0);
 130 
 131         obj = new Object[largeArraySize];
 132         WeakReference<Object> weakRef = new WeakReference<>(obj);
 133 
 134         MemoryUsage usage1 = mpool.getUsage();
 135         MemoryUsage peak1 = mpool.getPeakUsage();
 136         System.out.println("After the object is allocated: ");
 137         printMemoryUsage(usage1, peak1);
 138 
 139         if (usage1.getUsed() <= usage0.getUsed()) {
 140             throw new RuntimeException(
 141                 formatSize("Before allocation: used", usage0.getUsed()) +
 142                 " expected to be < " +
 143                 formatSize("After allocation: used", usage1.getUsed()));
 144         }
 145 
 146         if (peak1.getUsed() <= peak0.getUsed()) {
 147             throw new RuntimeException(
 148                 formatSize("Before allocation: peak", peak0.getUsed()) +
 149                 " expected to be < " +
 150                 formatSize("After allocation: peak", peak1.getUsed()));
 151         }
 152 
 153         // The object is now garbage and do a GC. Memory usage should drop.
 154         obj = null;
 155 
 156         // This will cause a sure shot GC unlike Runtime.gc() invoked by mbean.gc()
 157         while (weakRef.get() != null) {
 158             mbean.gc();
 159         }
 160 
 161         MemoryUsage usage2 = mpool.getUsage();
 162         MemoryUsage peak2 = mpool.getPeakUsage();
 163         System.out.println("After GC: ");
 164         printMemoryUsage(usage2, peak2);
 165 
 166         if (usage2.getUsed() >= usage1.getUsed()) {
 167             throw new RuntimeException(
 168                 formatSize("Before GC: used", usage1.getUsed()) + " " +
 169                 " expected to be > " +
 170                 formatSize("After GC: used", usage2.getUsed()));
 171         }
 172 
 173         mpool.resetPeakUsage();
 174 
 175         MemoryUsage usage3 = mpool.getUsage();
 176         MemoryUsage peak3 = mpool.getPeakUsage();
 177         System.out.println("After resetPeakUsage: ");
 178         printMemoryUsage(usage3, peak3);
 179 
 180         if (peak3.getUsed() != usage3.getUsed()) {
 181             throw new RuntimeException(
 182                 formatSize("After resetting peak: peak", peak3.getUsed()) + " " +
 183                 " expected to be equal to " +
 184                 formatSize("current used", usage3.getUsed()));
 185         }
 186 
 187         if (peak3.getUsed() >= peak2.getUsed()) {
 188             throw new RuntimeException(
 189                 formatSize("After resetting peak: peak", peak3.getUsed()) + " " +
 190                 " expected to be < " +
 191                 formatSize("previous peak", peak2.getUsed()));
 192         }
 193 
 194         System.out.println(RunUtil.successMessage);
 195     }
 196 
 197     private static String INDENT = "    ";
 198     private static void printMemoryUsage(MemoryUsage current, MemoryUsage peak) {
 199         System.out.println("Current Usage: ");
 200         MemoryUtil.printMemoryUsage(current);
 201         System.out.println("Peak Usage: ");
 202         MemoryUtil.printMemoryUsage(peak);
 203 
 204     }
 205     private static String formatSize(String name, long value) {
 206         StringBuffer buf = new StringBuffer(name + " = " + value);
 207         if (value > 0) {
 208             buf.append(" (" + (value >> 10) + "K)");
 209         }
 210         return buf.toString();
 211     }
 212 }