1 /* 2 * Copyright (c) 2003, 2018, 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 4959889 6992968 27 * @summary Basic unit test of memory management testing: 28 * 1) setCollectionUsageThreshold() and getCollectionUsageThreshold() 29 * 2) test notification emitted for two different memory pools. 30 * 31 * @author Mandy Chung 32 * 33 * @library /lib/testlibrary/ /test/lib 34 * @modules jdk.management 35 * @build jdk.testlibrary.* CollectionUsageThreshold MemoryUtil RunUtil 36 * @requires vm.opt.ExplicitGCInvokesConcurrent == "false" | vm.opt.ExplicitGCInvokesConcurrent == "null" 37 * @build sun.hotspot.WhiteBox 38 * @run driver ClassFileInstaller sun.hotspot.WhiteBox sun.hotspot.WhiteBox$WhiteBoxPermission 39 * @run main/othervm/timeout=300 -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI -Xbootclasspath/a:. CollectionUsageThreshold 40 */ 41 42 import java.util.*; 43 import java.util.concurrent.*; 44 import java.util.concurrent.atomic.AtomicInteger; 45 import javax.management.*; 46 import javax.management.openmbean.CompositeData; 47 import java.lang.management.*; 48 import static java.lang.management.MemoryNotificationInfo.*;; 49 import static java.lang.management.ManagementFactory.*; 50 51 import sun.hotspot.code.Compiler; 52 53 public class CollectionUsageThreshold { 54 private static final MemoryMXBean mm = getMemoryMXBean(); 55 private static final Map<String, PoolRecord> result = new HashMap<>(); 56 private static boolean trace = false; 57 private static volatile int numMemoryPools = 1; 58 private static final int NUM_GCS = 3; 59 private static final int THRESHOLD = 10; 60 private static volatile int numGCs = 0; 61 62 // semaphore to signal the arrival of a low memory notification 63 private static final Semaphore signals = new Semaphore(0); 64 // barrier for the main thread to wait until the checker thread 65 // finishes checking the low memory notification result 66 private static final CyclicBarrier barrier = new CyclicBarrier(2); 67 68 /** 69 * Run the test multiple times with different GC versions. 70 * First with default command line specified by the framework. 71 * Then with GC versions specified by the test. 72 */ 73 public static void main(String a[]) throws Throwable { 74 final String main = "CollectionUsageThreshold$TestMain"; 75 RunUtil.runTestKeepGcOpts(main); 76 RunUtil.runTestClearGcOpts(main, "-XX:+UseSerialGC"); 77 RunUtil.runTestClearGcOpts(main, "-XX:+UseParallelGC"); 78 RunUtil.runTestClearGcOpts(main, "-XX:+UseG1GC"); 79 if (!Compiler.isGraalEnabled()) { // Graal does not support CMS 80 RunUtil.runTestClearGcOpts(main, "-XX:+UseConcMarkSweepGC"); 81 } 82 } 83 84 static class PoolRecord { 85 private final MemoryPoolMXBean pool; 86 private final AtomicInteger listenerInvoked = new AtomicInteger(0); 87 private volatile long notifCount = 0; 88 PoolRecord(MemoryPoolMXBean p) { 89 this.pool = p; 90 } 91 int getListenerInvokedCount() { 92 return listenerInvoked.get(); 93 } 94 long getNotifCount() { 95 return notifCount; 96 } 97 MemoryPoolMXBean getPool() { 98 return pool; 99 } 100 void addNotification(MemoryNotificationInfo minfo) { 101 listenerInvoked.incrementAndGet(); 102 notifCount = minfo.getCount(); 103 } 104 } 105 106 static class SensorListener implements NotificationListener { 107 @Override 108 public void handleNotification(Notification notif, Object handback) { 109 String type = notif.getType(); 110 if (MEMORY_THRESHOLD_EXCEEDED.equals(type) || 111 MEMORY_COLLECTION_THRESHOLD_EXCEEDED.equals(type)) { 112 MemoryNotificationInfo minfo = MemoryNotificationInfo. 113 from((CompositeData) notif.getUserData()); 114 115 MemoryUtil.printMemoryNotificationInfo(minfo, type); 116 PoolRecord pr = (PoolRecord) result.get(minfo.getPoolName()); 117 if (pr == null) { 118 throw new RuntimeException("Pool " + minfo.getPoolName() + 119 " is not selected"); 120 } 121 if (!MEMORY_COLLECTION_THRESHOLD_EXCEEDED.equals(type)) { 122 throw new RuntimeException("Pool " + minfo.getPoolName() + 123 " got unexpected notification type: " + 124 type); 125 } 126 pr.addNotification(minfo); 127 System.out.println("notifying the checker thread to check result"); 128 signals.release(); 129 } 130 } 131 } 132 133 private static class TestMain { 134 public static void main(String args[]) throws Exception { 135 if (args.length > 0 && args[0].equals("trace")) { 136 trace = true; 137 } 138 139 List<MemoryPoolMXBean> pools = getMemoryPoolMXBeans(); 140 List<MemoryManagerMXBean> managers = getMemoryManagerMXBeans(); 141 142 if (trace) { 143 MemoryUtil.printMemoryPools(pools); 144 MemoryUtil.printMemoryManagers(managers); 145 } 146 147 // Find the Old generation which supports low memory detection 148 for (MemoryPoolMXBean p : pools) { 149 if (p.isUsageThresholdSupported() && p.isCollectionUsageThresholdSupported()) { 150 if (p.getName().toLowerCase().contains("perm")) { 151 // if we have a "perm gen" pool increase the number of expected 152 // memory pools by one. 153 numMemoryPools++; 154 } 155 PoolRecord pr = new PoolRecord(p); 156 result.put(p.getName(), pr); 157 if (result.size() == numMemoryPools) { 158 break; 159 } 160 } 161 } 162 if (result.size() != numMemoryPools) { 163 throw new RuntimeException("Unexpected number of selected pools"); 164 } 165 166 try { 167 // This test creates a checker thread responsible for checking 168 // the low memory notifications. It blocks until a permit 169 // from the signals semaphore is available. 170 Checker checker = new Checker("Checker thread"); 171 checker.setDaemon(true); 172 checker.start(); 173 174 for (PoolRecord pr : result.values()) { 175 pr.getPool().setCollectionUsageThreshold(THRESHOLD); 176 System.out.println("Collection usage threshold of " + 177 pr.getPool().getName() + " set to " + THRESHOLD); 178 } 179 180 SensorListener listener = new SensorListener(); 181 NotificationEmitter emitter = (NotificationEmitter) mm; 182 emitter.addNotificationListener(listener, null, null); 183 184 // The main thread invokes GC to trigger the VM to perform 185 // low memory detection and then waits until the checker thread 186 // finishes its work to check for a low-memory notification. 187 // 188 // At GC time, VM will issue low-memory notification and invoke 189 // the listener which will release a permit to the signals semaphore. 190 // When the checker thread acquires the permit and finishes 191 // checking the low-memory notification, it will also call 192 // barrier.await() to signal the main thread to resume its work. 193 for (int i = 0; i < NUM_GCS; i++) { 194 invokeGC(); 195 barrier.await(); 196 } 197 } finally { 198 // restore the default 199 for (PoolRecord pr : result.values()) { 200 pr.getPool().setCollectionUsageThreshold(0); 201 } 202 } 203 System.out.println(RunUtil.successMessage); 204 } 205 206 207 private static void invokeGC() { 208 System.out.println("Calling System.gc()"); 209 numGCs++; 210 mm.gc(); 211 212 if (trace) { 213 for (PoolRecord pr : result.values()) { 214 System.out.println("Usage after GC for: " + pr.getPool().getName()); 215 MemoryUtil.printMemoryUsage(pr.getPool().getUsage()); 216 } 217 } 218 } 219 } 220 221 static class Checker extends Thread { 222 Checker(String name) { 223 super(name); 224 }; 225 @Override 226 public void run() { 227 while (true) { 228 try { 229 signals.acquire(numMemoryPools); 230 checkResult(); 231 } catch (InterruptedException | BrokenBarrierException e) { 232 throw new RuntimeException(e); 233 } 234 } 235 } 236 private void checkResult() throws InterruptedException, BrokenBarrierException { 237 for (PoolRecord pr : result.values()) { 238 if (pr.getListenerInvokedCount() != numGCs) { 239 fail("Listeners invoked count = " + 240 pr.getListenerInvokedCount() + " expected to be " + 241 numGCs); 242 } 243 if (pr.getNotifCount() != numGCs) { 244 fail("Notif Count = " + 245 pr.getNotifCount() + " expected to be " + 246 numGCs); 247 } 248 249 long count = pr.getPool().getCollectionUsageThresholdCount(); 250 if (count != numGCs) { 251 fail("CollectionUsageThresholdCount = " + 252 count + " expected to be " + numGCs); 253 } 254 if (!pr.getPool().isCollectionUsageThresholdExceeded()) { 255 fail("isCollectionUsageThresholdExceeded" + 256 " expected to be true"); 257 } 258 } 259 // wait until the main thread is waiting for notification 260 barrier.await(); 261 System.out.println("notifying main thread to continue - result checking finished"); 262 } 263 264 private void fail(String msg) { 265 // reset the barrier to cause BrokenBarrierException to avoid hanging 266 barrier.reset(); 267 throw new RuntimeException(msg); 268 } 269 } 270 }