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