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