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 TestShrinkDefragmentedHeap
26  * @bug 8038423 8129590
27  * @summary Verify that heap shrinks after GC in the presence of fragmentation due to humongous objects
28  *     1. allocate small objects mixed with humongous ones
29  *        "ssssHssssHssssHssssHssssHssssHssssH"
30  *     2. release all allocated object except the last humongous one
31  *        "..................................H"
32  *     3. invoke gc and check that memory returned to the system (amount of committed memory got down)
33  *
34  * @library /test/lib /
35  * @modules java.base/jdk.internal.misc
36  *          java.management/sun.management
37  */
38 import java.lang.management.ManagementFactory;
39 import java.lang.management.MemoryUsage;
40 import java.util.ArrayList;
41 import java.util.List;
42 import java.text.NumberFormat;
43 import static jdk.test.lib.Asserts.*;
44 import jdk.test.lib.process.OutputAnalyzer;
45 import jdk.test.lib.process.ProcessTools;
46 import com.sun.management.HotSpotDiagnosticMXBean;
47 import gc.testlibrary.Helpers;
48 
49 public class TestShrinkDefragmentedHeap {
50     // Since we store all the small objects, they become old and old regions are also allocated at the bottom of the heap
51     // together with humongous regions. So if there are a lot of old regions in the lower part of the heap,
52     // the humongous regions will be allocated in the upper part of the heap anyway.
53     // To avoid this the Eden needs to be big enough to fit all the small objects.
54     private static final int INITIAL_HEAP_SIZE  = 200 * 1024 * 1024;
55     private static final int MINIMAL_YOUNG_SIZE = 190 * 1024 * 1024;
56     private static final int MAXIMUM_HEAP_SIZE  = 256 * 1024 * 1024;
57     private static final int REGION_SIZE        = 1 * 1024 * 1024;
58 
main(String[] args)59     public static void main(String[] args) throws Exception, Throwable {
60         ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
61                 "-XX:InitialHeapSize=" + INITIAL_HEAP_SIZE,
62                 "-Xmn" + MINIMAL_YOUNG_SIZE,
63                 "-Xmx" + MAXIMUM_HEAP_SIZE,
64                 "-XX:MinHeapFreeRatio=10",
65                 "-XX:MaxHeapFreeRatio=11",
66                 "-XX:+UseG1GC",
67                 "-XX:G1HeapRegionSize=" + REGION_SIZE,
68                 "-XX:-ExplicitGCInvokesConcurrent",
69                 "-verbose:gc",
70                 GCTest.class.getName()
71         );
72 
73         OutputAnalyzer output = ProcessTools.executeProcess(pb);
74         output.shouldHaveExitValue(0);
75     }
76 
77     static class GCTest {
78 
79         private static final String MIN_FREE_RATIO_FLAG_NAME = "MinHeapFreeRatio";
80         private static final String MAX_FREE_RATIO_FLAG_NAME = "MaxHeapFreeRatio";
81         private static final String NEW_SIZE_FLAG_NAME = "NewSize";
82 
83         private static final ArrayList<ArrayList<byte[]>> garbage = new ArrayList<>();
84 
85         private static final int SMALL_OBJS_SIZE  = 10 * 1024; // 10kB
86         private static final int SMALL_OBJS_COUNT = MINIMAL_YOUNG_SIZE / (SMALL_OBJS_SIZE-1);
87         private static final int ALLOCATE_COUNT = 3;
88         // try to put all humongous object into gap between min young size and initial heap size
89         // to avoid implicit GCs
90         private static final int HUMONG_OBJS_SIZE = (int) Math.max(
91                 (INITIAL_HEAP_SIZE - MINIMAL_YOUNG_SIZE) / ALLOCATE_COUNT / 4,
92                 REGION_SIZE * 1.1
93         );
94 
95         private static final long initialHeapSize = getHeapMemoryUsage().getUsed();
96 
main(String[] args)97         public static void main(String[] args) throws InterruptedException {
98             new GCTest().test();
99         }
100 
test()101         private void test() throws InterruptedException {
102             MemoryUsagePrinter.printMemoryUsage("init");
103 
104             allocate();
105             System.gc();
106             MemoryUsage muFull = getHeapMemoryUsage();
107             MemoryUsagePrinter.printMemoryUsage("allocated");
108 
109             free();
110             //Thread.sleep(1000); // sleep before measures due lags in JMX
111             MemoryUsage muFree = getHeapMemoryUsage();
112             MemoryUsagePrinter.printMemoryUsage("free");
113 
114             assertLessThan(muFree.getCommitted(), muFull.getCommitted(), prepareMessageCommittedIsNotLess() );
115         }
116 
allocate()117         private void allocate() {
118             System.out.format("Will allocate objects of small size = %s and humongous size = %s",
119                     MemoryUsagePrinter.NF.format(SMALL_OBJS_SIZE),
120                     MemoryUsagePrinter.NF.format(HUMONG_OBJS_SIZE)
121             );
122 
123             for (int i = 0; i < ALLOCATE_COUNT; i++) {
124                 ArrayList<byte[]> stuff = new ArrayList<>();
125                 allocateList(stuff, SMALL_OBJS_COUNT / ALLOCATE_COUNT, SMALL_OBJS_SIZE);
126                 garbage.add(stuff);
127 
128                 ArrayList<byte[]> humongousStuff = new ArrayList<>();
129                 allocateList(humongousStuff, 4, HUMONG_OBJS_SIZE);
130                 garbage.add(humongousStuff);
131             }
132         }
133 
free()134         private void free() {
135             // do not free last one list
136             garbage.subList(0, garbage.size() - 1).clear();
137 
138             // do not free last one element from last list
139             ArrayList stuff = garbage.get(garbage.size() - 1);
140             if (stuff.size() > 1) {
141                 stuff.subList(0, stuff.size() - 1).clear();
142             }
143             System.gc();
144         }
145 
prepareMessageCommittedIsNotLess()146         private String prepareMessageCommittedIsNotLess() {
147             return String.format(
148                     "committed free heap size is not less than committed full heap size, heap hasn't been shrunk?%n"
149                     + "%s = %s%n%s = %s",
150                     MIN_FREE_RATIO_FLAG_NAME,
151                     ManagementFactory.getPlatformMXBean(HotSpotDiagnosticMXBean.class)
152                         .getVMOption(MIN_FREE_RATIO_FLAG_NAME).getValue(),
153                     MAX_FREE_RATIO_FLAG_NAME,
154                     ManagementFactory.getPlatformMXBean(HotSpotDiagnosticMXBean.class)
155                         .getVMOption(MAX_FREE_RATIO_FLAG_NAME).getValue()
156             );
157         }
158 
allocateList(List garbage, int count, int size)159         private static void allocateList(List garbage, int count, int size) {
160             for (int i = 0; i < count; i++) {
161                 garbage.add(new byte[size]);
162             }
163         }
164     }
165 
getHeapMemoryUsage()166     static MemoryUsage getHeapMemoryUsage() {
167         return ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
168     }
169 
170     /**
171      * Prints memory usage to standard output
172      */
173     static class MemoryUsagePrinter {
174 
175         public static final NumberFormat NF = Helpers.numberFormatter();
176 
printMemoryUsage(String label)177         public static void printMemoryUsage(String label) {
178             MemoryUsage memusage = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
179             float freeratio = 1f - (float) memusage.getUsed() / memusage.getCommitted();
180             System.out.format("[%-24s] init: %-7s, used: %-7s, comm: %-7s, freeRatio ~= %.1f%%%n",
181                     label,
182                     NF.format(memusage.getInit()),
183                     NF.format(memusage.getUsed()),
184                     NF.format(memusage.getCommitted()),
185                     freeratio * 100
186             );
187         }
188     }
189 }
190