Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/test/jdk/java/lang/management/MemoryMXBean/LowMemoryTest.java
41155 views
1
/*
2
* Copyright (c) 2003, 2021, 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
26
* @bug 4530538
27
* @summary Basic unit test of memory management testing:
28
* 1) setUsageThreshold() and getUsageThreshold()
29
* 2) test low memory detection on the old generation.
30
* @author Mandy Chung
31
*
32
* @requires vm.gc == "null"
33
* @requires vm.opt.ExplicitGCInvokesConcurrent != "true"
34
* @requires vm.opt.DisableExplicitGC != "true"
35
* @library /test/lib
36
*
37
* @build LowMemoryTest MemoryUtil RunUtil
38
* @build sun.hotspot.WhiteBox
39
* @run driver jdk.test.lib.helpers.ClassFileInstaller sun.hotspot.WhiteBox
40
* @run main/othervm/timeout=600 -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI -Xbootclasspath/a:. LowMemoryTest
41
*/
42
43
import java.lang.management.*;
44
import java.util.*;
45
import java.util.concurrent.Phaser;
46
import javax.management.*;
47
import javax.management.openmbean.CompositeData;
48
import jdk.test.lib.JDKToolFinder;
49
import jdk.test.lib.process.ProcessTools;
50
import jdk.test.lib.Utils;
51
52
import sun.hotspot.code.Compiler;
53
54
public class LowMemoryTest {
55
private static final MemoryMXBean mm = ManagementFactory.getMemoryMXBean();
56
private static final List<MemoryPoolMXBean> pools = ManagementFactory.getMemoryPoolMXBeans();
57
private static final Phaser phaser = new Phaser(2);
58
private static MemoryPoolMXBean mpool = null;
59
private static boolean trace = false;
60
private static boolean testFailed = false;
61
private static final int NUM_TRIGGERS = 5;
62
private static final int NUM_CHUNKS = 2;
63
private static final int YOUNG_GEN_SIZE = 8 * 1024 * 1024;
64
private static long chunkSize;
65
private static final String classMain = "LowMemoryTest$TestMain";
66
67
/**
68
* Run the test multiple times with different GC versions.
69
* First with default command line specified by the framework.
70
* Then with GC versions specified by the test.
71
*/
72
public static void main(String a[]) throws Throwable {
73
// Use a low young gen size to ensure that the
74
// allocated objects are put in the old gen.
75
final String nmFlag = "-Xmn" + YOUNG_GEN_SIZE;
76
// Using large pages will change the young gen size,
77
// make sure we don't use them for this test.
78
final String lpFlag = "-XX:-UseLargePages";
79
// Prevent G1 from selecting a large heap region size,
80
// since that would change the young gen size.
81
final String g1Flag = "-XX:G1HeapRegionSize=1m";
82
83
// Runs the test collecting subprocess I/O while it's running.
84
traceTest(classMain + ", -XX:+UseSerialGC", nmFlag, lpFlag, "-XX:+UseSerialGC");
85
traceTest(classMain + ", -XX:+UseParallelGC", nmFlag, lpFlag, "-XX:+UseParallelGC");
86
traceTest(classMain + ", -XX:+UseG1GC", nmFlag, lpFlag, "-XX:+UseG1GC", g1Flag);
87
}
88
89
/*
90
* Creating command-line for running subprocess JVM:
91
*
92
* JVM command line is like:
93
* {test_jdk}/bin/java {defaultopts} -cp {test.class.path} {testopts} main
94
*
95
* {defaultopts} are the default java options set by the framework.
96
*
97
* @param testOpts java options specified by the test.
98
*/
99
private static List<String> buildCommandLine(String... testOpts) {
100
List<String> opts = new ArrayList<>();
101
opts.add(JDKToolFinder.getJDKTool("java"));
102
opts.addAll(Arrays.asList(Utils.getTestJavaOpts()));
103
opts.add("-cp");
104
opts.add(System.getProperty("test.class.path", "test.class.path"));
105
opts.add("-Xlog:gc*=debug");
106
opts.addAll(Arrays.asList(testOpts));
107
opts.add(classMain);
108
109
return opts;
110
}
111
112
/**
113
* Runs LowMemoryTest$TestMain with the passed options and redirects subprocess
114
* standard I/O to the current (parent) process. This provides a trace of what
115
* happens in the subprocess while it is runnning (and before it terminates).
116
*
117
* @param prefixName the prefix string for redirected outputs
118
* @param testOpts java options specified by the test.
119
*/
120
private static void traceTest(String prefixName,
121
String... testOpts)
122
throws Throwable {
123
124
// Building command-line
125
List<String> opts = buildCommandLine(testOpts);
126
127
// We activate all tracing in subprocess
128
opts.add("trace");
129
130
// Launch separate JVM subprocess
131
String[] optsArray = opts.toArray(new String[0]);
132
ProcessBuilder pb = new ProcessBuilder(optsArray);
133
System.out.println("\n========= Tracing of subprocess " + prefixName + " =========");
134
Process p = ProcessTools.startProcess(prefixName, pb);
135
136
// Handling end of subprocess
137
try {
138
int exitCode = p.waitFor();
139
if (exitCode != 0) {
140
throw new RuntimeException(
141
"Subprocess unexpected exit value of [" + exitCode + "]. Expected 0.\n");
142
}
143
} catch (InterruptedException e) {
144
throw new RuntimeException("Parent process interrupted with exception : \n " + e + " :" );
145
}
146
147
148
}
149
150
private static volatile boolean listenerInvoked = false;
151
static class SensorListener implements NotificationListener {
152
@Override
153
public void handleNotification(Notification notif, Object handback) {
154
String type = notif.getType();
155
if (type.equals(MemoryNotificationInfo.MEMORY_THRESHOLD_EXCEEDED) ||
156
type.equals(MemoryNotificationInfo.
157
MEMORY_COLLECTION_THRESHOLD_EXCEEDED)) {
158
159
MemoryNotificationInfo minfo = MemoryNotificationInfo.
160
from((CompositeData) notif.getUserData());
161
162
MemoryUtil.printMemoryNotificationInfo(minfo, type);
163
listenerInvoked = true;
164
}
165
}
166
}
167
168
static class TestListener implements NotificationListener {
169
private int triggers = 0;
170
private final long[] count = new long[NUM_TRIGGERS * 2];
171
private final long[] usedMemory = new long[NUM_TRIGGERS * 2];
172
173
@Override
174
public void handleNotification(Notification notif, Object handback) {
175
MemoryNotificationInfo minfo = MemoryNotificationInfo.
176
from((CompositeData) notif.getUserData());
177
count[triggers] = minfo.getCount();
178
usedMemory[triggers] = minfo.getUsage().getUsed();
179
triggers++;
180
}
181
public void checkResult() throws Exception {
182
if (!checkValue(triggers, NUM_TRIGGERS)) {
183
throw new RuntimeException("Unexpected number of triggers = " +
184
triggers + " but expected to be " + NUM_TRIGGERS);
185
}
186
187
for (int i = 0; i < triggers; i++) {
188
if (!checkValue(count[i], i + 1)) {
189
throw new RuntimeException("Unexpected count of" +
190
" notification #" + i +
191
" count = " + count[i] +
192
" but expected to be " + (i+1));
193
}
194
if (usedMemory[i] < newThreshold) {
195
throw new RuntimeException("Used memory = " +
196
usedMemory[i] + " is less than the threshold = " +
197
newThreshold);
198
}
199
}
200
}
201
202
private boolean checkValue(int value, int target) {
203
return checkValue((long)value, target);
204
}
205
206
private boolean checkValue(long value, int target) {
207
return value == target;
208
}
209
}
210
211
private static long newThreshold;
212
213
private static class TestMain {
214
public static void main(String args[]) throws Exception {
215
if (args.length > 0 && args[0].equals("trace")) {
216
trace = true;
217
}
218
219
// Find the Old generation which supports low memory detection
220
ListIterator iter = pools.listIterator();
221
while (iter.hasNext()) {
222
MemoryPoolMXBean p = (MemoryPoolMXBean) iter.next();
223
if (p.getType() == MemoryType.HEAP &&
224
p.isUsageThresholdSupported()) {
225
mpool = p;
226
if (trace) {
227
System.out.println("Selected memory pool for low memory " +
228
"detection.");
229
MemoryUtil.printMemoryPool(mpool);
230
}
231
break;
232
}
233
}
234
235
TestListener listener = new TestListener();
236
SensorListener l2 = new SensorListener();
237
NotificationEmitter emitter = (NotificationEmitter) mm;
238
emitter.addNotificationListener(listener, null, null);
239
emitter.addNotificationListener(l2, null, null);
240
241
Thread allocator = new AllocatorThread();
242
Thread sweeper = new SweeperThread();
243
244
// The chunk size needs to be larger than YOUNG_GEN_SIZE,
245
// otherwise we will get intermittent failures when objects
246
// end up in the young gen instead of the old gen.
247
final long epsilon = 1024;
248
chunkSize = YOUNG_GEN_SIZE + epsilon;
249
250
MemoryUsage mu = mpool.getUsage();
251
newThreshold = mu.getUsed() + (chunkSize * NUM_CHUNKS);
252
253
// Sanity check. Make sure the new threshold isn't too large.
254
// Tweak the test if this fails.
255
final long headRoom = chunkSize * 2;
256
final long max = mu.getMax();
257
if (max != -1 && newThreshold > max - headRoom) {
258
throw new RuntimeException("TEST FAILED: newThreshold: " + newThreshold +
259
" is too near the maximum old gen size: " + max +
260
" used: " + mu.getUsed() + " headRoom: " + headRoom);
261
}
262
263
System.out.println("Setting threshold for " + mpool.getName() +
264
" from " + mpool.getUsageThreshold() + " to " + newThreshold +
265
". Current used = " + mu.getUsed());
266
267
mpool.setUsageThreshold(newThreshold);
268
269
if (mpool.getUsageThreshold() != newThreshold) {
270
throw new RuntimeException("TEST FAILED: " +
271
"Threshold for Memory pool " + mpool.getName() +
272
"is " + mpool.getUsageThreshold() + " but expected to be" +
273
newThreshold);
274
}
275
276
277
allocator.start();
278
// Force Allocator start first
279
phaser.arriveAndAwaitAdvance();
280
sweeper.start();
281
282
283
try {
284
allocator.join();
285
// Wait until AllocatorThread's done
286
phaser.arriveAndAwaitAdvance();
287
sweeper.join();
288
} catch (InterruptedException e) {
289
System.out.println("Unexpected exception:" + e);
290
testFailed = true;
291
}
292
293
listener.checkResult();
294
295
if (testFailed)
296
throw new RuntimeException("TEST FAILED.");
297
298
System.out.println(RunUtil.successMessage);
299
}
300
}
301
302
private static void goSleep(long ms) {
303
try {
304
Thread.sleep(ms);
305
} catch (InterruptedException e) {
306
System.out.println("Unexpected exception:" + e);
307
testFailed = true;
308
}
309
}
310
311
private static final List<Object> objectPool = new ArrayList<>();
312
static class AllocatorThread extends Thread {
313
public void doTask() {
314
int iterations = 0;
315
int numElements = (int) (chunkSize / 4); // minimal object size
316
while (!listenerInvoked || mpool.getUsage().getUsed() < mpool.getUsageThreshold()) {
317
iterations++;
318
if (trace) {
319
System.out.println(" Iteration " + iterations +
320
": before allocation " +
321
mpool.getUsage().getUsed());
322
}
323
324
Object[] o = new Object[numElements];
325
if (iterations <= NUM_CHUNKS) {
326
// only hold a reference to the first NUM_CHUNKS
327
// allocated objects
328
objectPool.add(o);
329
}
330
331
if (trace) {
332
System.out.println(" " +
333
" after allocation " +
334
mpool.getUsage().getUsed());
335
}
336
goSleep(100);
337
}
338
}
339
@Override
340
public void run() {
341
for (int i = 1; i <= NUM_TRIGGERS; i++) {
342
// Sync with SweeperThread's second phase.
343
phaser.arriveAndAwaitAdvance();
344
System.out.println("AllocatorThread is doing task " + i +
345
" phase " + phaser.getPhase());
346
doTask();
347
// Sync with SweeperThread's first phase.
348
phaser.arriveAndAwaitAdvance();
349
System.out.println("AllocatorThread done task " + i +
350
" phase " + phaser.getPhase());
351
if (testFailed) {
352
return;
353
}
354
}
355
}
356
}
357
358
static class SweeperThread extends Thread {
359
private void doTask() {
360
int iterations = 0;
361
if (trace) {
362
System.out.println("SweeperThread clearing allocated objects.");
363
}
364
365
for (; mpool.getUsage().getUsed() >=
366
mpool.getUsageThreshold();) {
367
// clear all allocated objects and invoke GC
368
objectPool.clear();
369
mm.gc();
370
371
if (trace) {
372
iterations++;
373
System.out.println("SweeperThread called " + iterations +
374
" time(s) MemoryMXBean.gc().");
375
}
376
377
goSleep(100);
378
}
379
}
380
381
@Override
382
public void run() {
383
for (int i = 1; i <= NUM_TRIGGERS; i++) {
384
// Sync with AllocatorThread's first phase.
385
phaser.arriveAndAwaitAdvance();
386
System.out.println("SweeperThread is doing task " + i +
387
" phase " + phaser.getPhase());
388
389
doTask();
390
391
listenerInvoked = false;
392
393
// Sync with AllocatorThread's second phase.
394
phaser.arriveAndAwaitAdvance();
395
System.out.println("SweeperThread done task " + i +
396
" phase " + phaser.getPhase());
397
if (testFailed) return;
398
}
399
}
400
}
401
}
402
403