1 /*
   2  * Copyright (c) 2014, 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 /**
  25  * @test TestHumongousShrinkHeap
  26  * @bug 8036025 8056043
  27  * @requires vm.gc.G1
  28  * @summary Verify that heap shrinks after GC in the presence of fragmentation
  29  * due to humongous objects
  30  * @library /test/lib
  31  * @modules java.base/jdk.internal.misc
  32  * @modules java.management/sun.management
  33  * @run main/othervm -XX:-ExplicitGCInvokesConcurrent -XX:MinHeapFreeRatio=10
  34  * -XX:MaxHeapFreeRatio=12 -XX:+UseG1GC -XX:G1HeapRegionSize=1M -verbose:gc
  35  * TestHumongousShrinkHeap
  36  */
  37 
  38 import com.sun.management.HotSpotDiagnosticMXBean;
  39 import java.lang.management.ManagementFactory;
  40 import java.lang.management.MemoryUsage;
  41 import java.util.ArrayList;
  42 import java.util.List;
  43 import static jdk.test.lib.Asserts.*;
  44 
  45 public class TestHumongousShrinkHeap {
  46 
  47     public static final String MIN_FREE_RATIO_FLAG_NAME = "MinHeapFreeRatio";
  48     public static final String MAX_FREE_RATIO_FLAG_NAME = "MaxHeapFreeRatio";
  49 
  50     private static final List<List<byte[]>> garbage = new ArrayList();
  51     private static final int REGION_SIZE = 1024 * 1024; // 1M
  52     private static final int LISTS_COUNT = 10;
  53     private static final int HUMON_SIZE = Math.round(.9f * REGION_SIZE);
  54     private static final long AVAILABLE_MEMORY
  55                               = Runtime.getRuntime().freeMemory();
  56     private static final int HUMON_COUNT
  57                              = (int) ((AVAILABLE_MEMORY / HUMON_SIZE)
  58             / LISTS_COUNT);
  59 
  60 
  61     public static void main(String[] args) {
  62         if (HUMON_COUNT == 0) {
  63             System.out.println("Skipped. Heap is too small");
  64             return;
  65         }
  66         System.out.format("Running with %s max heap size. "
  67                 + "Will allocate humongous object of %s size %d times.%n",
  68                 MemoryUsagePrinter.humanReadableByteCount(AVAILABLE_MEMORY, false),
  69                 MemoryUsagePrinter.humanReadableByteCount(HUMON_SIZE, false),
  70                 HUMON_COUNT
  71         );
  72         new TestHumongousShrinkHeap().test();
  73     }
  74 
  75     private final void test() {
  76         System.gc();
  77         MemoryUsagePrinter.printMemoryUsage("init");
  78 
  79         allocate();
  80         MemoryUsagePrinter.printMemoryUsage("allocated");
  81         MemoryUsage muFull = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
  82 
  83         free();
  84         MemoryUsagePrinter.printMemoryUsage("free");
  85         MemoryUsage muFree = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
  86 
  87         assertLessThan(muFree.getCommitted(), muFull.getCommitted(), String.format(
  88                 "committed free heap size is not less than committed full heap size, heap hasn't been shrunk?%n"
  89                 + "%s = %s%n%s = %s",
  90                 MIN_FREE_RATIO_FLAG_NAME,
  91                 ManagementFactory.getPlatformMXBean(HotSpotDiagnosticMXBean.class)
  92                     .getVMOption(MIN_FREE_RATIO_FLAG_NAME).getValue(),
  93                 MAX_FREE_RATIO_FLAG_NAME,
  94                 ManagementFactory.getPlatformMXBean(HotSpotDiagnosticMXBean.class)
  95                     .getVMOption(MAX_FREE_RATIO_FLAG_NAME).getValue()
  96         ));
  97     }
  98 
  99     private void allocate() {
 100 
 101         for (int i = 0; i < LISTS_COUNT; i++) {
 102             List<byte[]> stuff = new ArrayList();
 103             allocateList(stuff, HUMON_COUNT, HUMON_SIZE);
 104             MemoryUsagePrinter.printMemoryUsage("allocate #" + (i+1));
 105             garbage.add(stuff);
 106         }
 107     }
 108 
 109     private void free() {
 110         // do not free last one list
 111         garbage.subList(0, garbage.size() - 1).clear();
 112 
 113         // do not free last one element from last list
 114         List stuff = garbage.get(garbage.size() - 1);
 115         stuff.subList(0, stuff.size() - 1).clear();
 116         System.gc();
 117     }
 118 
 119     private static void allocateList(List garbage, int count, int size) {
 120         for (int i = 0; i < count; i++) {
 121             garbage.add(new byte[size]);
 122         }
 123     }
 124 }
 125 
 126 /**
 127  * Prints memory usage to standard output
 128  */
 129 class MemoryUsagePrinter {
 130 
 131     public static String humanReadableByteCount(long bytes, boolean si) {
 132         int unit = si ? 1000 : 1024;
 133         if (bytes < unit) {
 134             return bytes + " B";
 135         }
 136         int exp = (int) (Math.log(bytes) / Math.log(unit));
 137         String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp - 1) + (si ? "" : "i");
 138         return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre);
 139     }
 140 
 141     public static void printMemoryUsage(String label) {
 142         MemoryUsage memusage = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
 143         float freeratio = 1f - (float) memusage.getUsed() / memusage.getCommitted();
 144         System.out.format("[%-24s] init: %-7s, used: %-7s, comm: %-7s, freeRatio ~= %.1f%%%n",
 145                 label,
 146                 humanReadableByteCount(memusage.getInit(), false),
 147                 humanReadableByteCount(memusage.getUsed(), false),
 148                 humanReadableByteCount(memusage.getCommitted(), false),
 149                 freeratio * 100
 150         );
 151     }
 152 }