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