Path: blob/master/test/jdk/java/lang/management/MemoryMXBean/LowMemoryTest2.java
41155 views
/*1* Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223/*24* Test low memory detection of non-heap memory pool.25*26* The test set a listener to be notified when any of the non-heap pools27* exceed 80%. It then starts a thread that continuously loads classes.28* In the HotSpot implementation this causes metaspace to be consumed.29* Test completes when we the notification is received or an OutOfMemory30* is generated.31*/3233import java.lang.management.*;34import javax.management.*;35import javax.management.openmbean.CompositeData;36import java.util.*;3738public class LowMemoryTest2 {3940private static volatile boolean listenerInvoked = false;4142private static String INDENT = " ";4344static class SensorListener implements NotificationListener {45public void handleNotification(Notification notif, Object handback) {46String type = notif.getType();47if (type.equals(MemoryNotificationInfo.MEMORY_THRESHOLD_EXCEEDED) ||48type.equals(MemoryNotificationInfo.49MEMORY_COLLECTION_THRESHOLD_EXCEEDED)) {50listenerInvoked = true;51MemoryNotificationInfo minfo = MemoryNotificationInfo.52from((CompositeData) notif.getUserData());5354System.out.print("Notification for " + minfo.getPoolName());55System.out.print(" [type = " + type);56System.out.println(" count = " + minfo.getCount() + "]");57System.out.println(INDENT + "usage = " + minfo.getUsage());58}59}60}6162// Loads classes Test100001, Test100002, .... until OutOfMemoryErrror or63// low memory notification6465static class BoundlessLoaderThread extends ClassLoader implements Runnable {66private final List<MemoryPoolMXBean> pools;6768public BoundlessLoaderThread(List<MemoryPoolMXBean> pools) {69this.pools = pools;70}7172static int count = 100000;7374Class loadNext() {7576// public class TestNNNNNN extends java.lang.Object{77// public TestNNNNNN();78// Code:79// 0: aload_080// 1: invokespecial #1; //Method java/lang/Object."<init>":()V81// 4: return82// }8384int begin[] = {850xca, 0xfe, 0xba, 0xbe, 0x00, 0x00, 0x00, 0x30,860x00, 0x0a, 0x0a, 0x00, 0x03, 0x00, 0x07, 0x07,870x00, 0x08, 0x07, 0x00, 0x09, 0x01, 0x00, 0x06,880x3c, 0x69, 0x6e, 0x69, 0x74, 0x3e, 0x01, 0x00,890x03, 0x28, 0x29, 0x56, 0x01, 0x00, 0x04, 0x43,900x6f, 0x64, 0x65, 0x0c, 0x00, 0x04, 0x00, 0x05,910x01, 0x00, 0x0a, 0x54, 0x65, 0x73, 0x74 };9293int end [] = {940x01, 0x00, 0x10,950x6a, 0x61, 0x76, 0x61, 0x2f, 0x6c, 0x61, 0x6e,960x67, 0x2f, 0x4f, 0x62, 0x6a, 0x65, 0x63, 0x74,970x00, 0x21, 0x00, 0x02, 0x00, 0x03, 0x00, 0x00,980x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x04,990x00, 0x05, 0x00, 0x01, 0x00, 0x06, 0x00, 0x00,1000x00, 0x11, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00,1010x00, 0x05, 0x2a, 0xb7, 0x00, 0x01, 0xb1, 0x00,1020x00, 0x00, 0x00, 0x00, 0x00 };103104105// TestNNNNNN106107int load_count = count++;108if (load_count > 999999) {109// The test will create a corrupt class file if the count110// exceeds 999999. Fix the test if this exception is thrown.111throw new RuntimeException("Load count exceeded");112}113114String name = "Test" + Integer.toString(load_count);115116byte value[];117try {118value = name.substring(4).getBytes("UTF-8");119} catch (java.io.UnsupportedEncodingException x) {120throw new Error();121}122123// construct class file124125int len = begin.length + value.length + end.length;126byte b[] = new byte[len];127int i, pos=0;128for (i=0; i<begin.length; i++) {129b[pos++] = (byte)begin[i];130}131for (i=0; i<value.length; i++) {132b[pos++] = value[i];133}134for (i=0; i<end.length; i++) {135b[pos++] = (byte)end[i];136}137138return defineClass(name, b, 0, b.length);139}140141/*142* Load classes until MemoryPoolMXBean.getUsageThresholdCount() > 0.143* Then wait for the memory threshold notification to be received.144*/145public void run() {146// Load classes until MemoryPoolMXBean.getUsageThresholdCount() > 0147boolean isThresholdCountSet = false;148try {149while (!isThresholdCountSet) {150// the classes are small so we load 10 at a time151for (int i=0; i<10; i++) {152loadNext();153}154155if (isAnyUsageAboveThreshold(pools)) {156// UsageThresholdCount is only updated during GC.157// Force GC to update counters.158// If we don't force a GC we may get an159// OutOfMemoryException before the counters are updated.160System.out.println("Force GC");161System.gc();162}163isThresholdCountSet = isAnyThresholdCountSet(pools);164}165} catch (OutOfMemoryError e) {166e.printStackTrace();167MemoryUtil.printMemoryPools(pools);168throw e;169}170171System.out.println("thresholdExceeded. Waiting for notification");172while (!listenerInvoked) {173try {174Thread.currentThread().sleep(10);175} catch (InterruptedException x) {}176}177}178179private boolean isAnyUsageAboveThreshold(List<MemoryPoolMXBean> pools) {180for (MemoryPoolMXBean p : pools) {181if (p.isUsageThresholdExceeded()) {182System.out.println("isAnyUsageAboveThreshold is true for " + p.getName());183MemoryUtil.printMemoryPool(p);184return true;185}186}187return false;188}189190private boolean isAnyThresholdCountSet(List<MemoryPoolMXBean> pools) {191for (MemoryPoolMXBean p : pools) {192if (p.getUsageThresholdCount() > 0) {193System.out.println("isAnyThresholdCountSet is true for " + p.getName());194MemoryUtil.printMemoryPool(p);195return true;196}197}198return false;199}200}201202public static void main(String args[]) {203// The pools list will only contain the pools that we are interested in.204List<MemoryPoolMXBean> pools = new ArrayList<MemoryPoolMXBean>();205206// Set threshold of 80% of all NON_HEAP memory pools207// In the Hotspot implementation this means we should get a notification208// if the CodeCache or metaspace fills up.209210for (MemoryPoolMXBean p : ManagementFactory.getMemoryPoolMXBeans()) {211if (p.getType() == MemoryType.NON_HEAP && p.isUsageThresholdSupported()) {212213// set threshold214MemoryUsage mu = p.getUsage();215long max = mu.getMax();216if (max < 0) {217throw new RuntimeException("There is no maximum set for "218+ p.getName() + " memory pool so the test is invalid");219}220long threshold = (max * 80) / 100;221222p.setUsageThreshold(threshold);223pools.add(p);224225System.out.println("Selected memory pool for low memory " +226"detection.");227MemoryUtil.printMemoryPool(p);228229}230}231232233// Install the listener234235MemoryMXBean mm = ManagementFactory.getMemoryMXBean();236SensorListener l2 = new SensorListener();237238NotificationEmitter emitter = (NotificationEmitter) mm;239emitter.addNotificationListener(l2, null, null);240241// Start the thread loading classes242243Thread thr = new Thread(new BoundlessLoaderThread(pools));244thr.start();245246// Wait for the thread to terminate247try {248thr.join();249} catch (InterruptedException x) {250throw new RuntimeException(x);251}252253if (listenerInvoked) {254System.out.println("Notification received - test passed.");255} else {256throw new RuntimeException("Test failed - notification not received!");257}258}259260}261262263