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     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  *
  31  * @author  Mandy Chung
  32  *
  33  * @library /lib/testlibrary/
  34  * @build jdk.testlibrary.* LowMemoryTest MemoryUtil RunUtil
  35  * @run main/timeout=600 LowMemoryTest
  36  */
  37 
  38 import java.lang.management.*;
  39 import java.util.*;
  40 import java.util.concurrent.Phaser;
  41 import javax.management.*;
  42 import javax.management.openmbean.CompositeData;
  43 
  44 public class LowMemoryTest {
  45     private static final MemoryMXBean mm = ManagementFactory.getMemoryMXBean();
  46     private static final List<MemoryPoolMXBean> pools = ManagementFactory.getMemoryPoolMXBeans();
  47     private static final Phaser phaser = new Phaser(2);
  48     private static MemoryPoolMXBean mpool = null;
  49     private static boolean trace = false;
  50     private static boolean testFailed = false;
  51     private static final int NUM_TRIGGERS = 5;
  52     private static final int NUM_CHUNKS = 2;
  53     private static final int YOUNG_GEN_SIZE = 8 * 1024 * 1024;
  54     private static long chunkSize;
  55 
  56     /**
  57      * Run the test multiple times with different GC versions.
  58      * First with default command line specified by the framework.
  59      * Then with GC versions specified by the test.
  60      */
  61     public static void main(String a[]) throws Throwable {
  62         final String main = "LowMemoryTest$TestMain";
  63         // Use a low young gen size to ensure that the
  64         // allocated objects are put in the old gen.
  65         final String nmFlag = "-Xmn" + YOUNG_GEN_SIZE;
  66         // Using large pages will change the young gen size,
  67         // make sure we don't use them for this test.
  68         final String lpFlag = "-XX:-UseLargePages";
  69         // Prevent G1 from selecting a large heap region size,
  70         // since that would change the young gen size.
  71         final String g1Flag = "-XX:G1HeapRegionSize=1m";
  72         RunUtil.runTestClearGcOpts(main, nmFlag, lpFlag, "-XX:+UseSerialGC");
  73         RunUtil.runTestClearGcOpts(main, nmFlag, lpFlag, "-XX:+UseParallelGC");
  74         RunUtil.runTestClearGcOpts(main, nmFlag, lpFlag, "-XX:+UseG1GC", g1Flag);
  75         RunUtil.runTestClearGcOpts(main, nmFlag, lpFlag, "-XX:+UseConcMarkSweepGC");
  76     }
  77 
  78     private static volatile boolean listenerInvoked = false;
  79     static class SensorListener implements NotificationListener {
  80         @Override
  81         public void handleNotification(Notification notif, Object handback) {
  82             String type = notif.getType();
  83             if (type.equals(MemoryNotificationInfo.MEMORY_THRESHOLD_EXCEEDED) ||
  84                 type.equals(MemoryNotificationInfo.
  85                     MEMORY_COLLECTION_THRESHOLD_EXCEEDED)) {
  86 
  87                 MemoryNotificationInfo minfo = MemoryNotificationInfo.
  88                     from((CompositeData) notif.getUserData());
  89 
  90                 MemoryUtil.printMemoryNotificationInfo(minfo, type);
  91                 listenerInvoked = true;
  92             }
  93         }
  94     }
  95 
  96     static class TestListener implements NotificationListener {
  97         private int triggers = 0;
  98         private final long[] count = new long[NUM_TRIGGERS * 2];
  99         private final long[] usedMemory = new long[NUM_TRIGGERS * 2];
 100         @Override
 101         public void handleNotification(Notification notif, Object handback) {
 102             MemoryNotificationInfo minfo = MemoryNotificationInfo.
 103                 from((CompositeData) notif.getUserData());
 104             count[triggers] = minfo.getCount();
 105             usedMemory[triggers] = minfo.getUsage().getUsed();
 106             triggers++;
 107         }
 108         public void checkResult() throws Exception {
 109             if (triggers != NUM_TRIGGERS) {
 110                 throw new RuntimeException("Unexpected number of triggers = " +
 111                     triggers + " but expected to be " + NUM_TRIGGERS);
 112             }
 113 
 114             for (int i = 0; i < triggers; i++) {
 115                 if (count[i] != i+1) {
 116                     throw new RuntimeException("Unexpected count of" +
 117                         " notification #" + i +
 118                         " count = " + count[i] +
 119                         " but expected to be " + (i+1));
 120                 }
 121                 if (usedMemory[i] < newThreshold) {
 122                     throw new RuntimeException("Used memory = " +
 123                         usedMemory[i] + " is less than the threshold = " +
 124                         newThreshold);
 125                 }
 126             }
 127         }
 128     }
 129 
 130     private static long newThreshold;
 131 
 132     private static class TestMain {
 133         public static void main(String args[]) throws Exception {
 134             if (args.length > 0 && args[0].equals("trace")) {
 135                 trace = true;
 136             }
 137 
 138             // Find the Old generation which supports low memory detection
 139             ListIterator iter = pools.listIterator();
 140             while (iter.hasNext()) {
 141                 MemoryPoolMXBean p = (MemoryPoolMXBean) iter.next();
 142                 if (p.getType() == MemoryType.HEAP &&
 143                     p.isUsageThresholdSupported()) {
 144                     mpool = p;
 145                     if (trace) {
 146                         System.out.println("Selected memory pool for low memory " +
 147                             "detection.");
 148                         MemoryUtil.printMemoryPool(mpool);
 149                     }
 150                     break;
 151                 }
 152             }
 153 
 154             TestListener listener = new TestListener();
 155             SensorListener l2 = new SensorListener();
 156             NotificationEmitter emitter = (NotificationEmitter) mm;
 157             emitter.addNotificationListener(listener, null, null);
 158             emitter.addNotificationListener(l2, null, null);
 159 
 160             Thread allocator = new AllocatorThread();
 161             Thread sweeper = new SweeperThread();
 162 
 163             // The chunk size needs to be larger than YOUNG_GEN_SIZE,
 164             // otherwise we will get intermittent failures when objects
 165             // end up in the young gen instead of the old gen.
 166             final long epsilon = 1024;
 167             chunkSize = YOUNG_GEN_SIZE + epsilon;
 168 
 169             MemoryUsage mu = mpool.getUsage();
 170             newThreshold = mu.getUsed() + (chunkSize * NUM_CHUNKS);
 171 
 172             // Sanity check. Make sure the new threshold isn't too large.
 173             // Tweak the test if this fails.
 174             final long headRoom = chunkSize * 2;
 175             final long max = mu.getMax();
 176             if (max != -1 && newThreshold > max - headRoom) {
 177                 throw new RuntimeException("TEST FAILED: newThreshold: " + newThreshold +
 178                         " is too near the maximum old gen size: " + max +
 179                         " used: " + mu.getUsed() + " headRoom: " + headRoom);
 180             }
 181 
 182             System.out.println("Setting threshold for " + mpool.getName() +
 183                 " from " + mpool.getUsageThreshold() + " to " + newThreshold +
 184                 ".  Current used = " + mu.getUsed());
 185             mpool.setUsageThreshold(newThreshold);
 186 
 187             if (mpool.getUsageThreshold() != newThreshold) {
 188                 throw new RuntimeException("TEST FAILED: " +
 189                 "Threshold for Memory pool " + mpool.getName() +
 190                 "is " + mpool.getUsageThreshold() + " but expected to be" +
 191                 newThreshold);
 192             }
 193 
 194 
 195             allocator.start();
 196             // Force Allocator start first
 197             phaser.arriveAndAwaitAdvance();
 198             sweeper.start();
 199 
 200 
 201             try {
 202                 allocator.join();
 203                 // Wait until AllocatorThread's done
 204                 phaser.arriveAndAwaitAdvance();
 205                 sweeper.join();
 206             } catch (InterruptedException e) {
 207                 System.out.println("Unexpected exception:" + e);
 208                 testFailed = true;
 209             }
 210 
 211             listener.checkResult();
 212 
 213             if (testFailed)
 214                 throw new RuntimeException("TEST FAILED.");
 215 
 216             System.out.println(RunUtil.successMessage);
 217 
 218         }
 219     }
 220 
 221     private static void goSleep(long ms) {
 222         try {
 223             Thread.sleep(ms);
 224         } catch (InterruptedException e) {
 225             System.out.println("Unexpected exception:" + e);
 226             testFailed = true;
 227         }
 228     }
 229 
 230     private static final List<Object> objectPool = new ArrayList<>();
 231     static class AllocatorThread extends Thread {
 232         public void doTask() {
 233             int iterations = 0;
 234             int numElements = (int) (chunkSize / 4); // minimal object size
 235             while (!listenerInvoked || mpool.getUsage().getUsed() < mpool.getUsageThreshold()) {
 236                 iterations++;
 237                 if (trace) {
 238                     System.out.println("   Iteration " + iterations +
 239                         ": before allocation " +
 240                         mpool.getUsage().getUsed());
 241                 }
 242 
 243                 Object[] o = new Object[numElements];
 244                 if (iterations <= NUM_CHUNKS) {
 245                     // only hold a reference to the first NUM_CHUNKS
 246                     // allocated objects
 247                     objectPool.add(o);
 248                 }
 249 
 250                 if (trace) {
 251                     System.out.println("               " +
 252                         "  after allocation " +
 253                         mpool.getUsage().getUsed());
 254                 }
 255                 goSleep(100);
 256             }
 257         }
 258         @Override
 259         public void run() {
 260             for (int i = 1; i <= NUM_TRIGGERS; i++) {
 261                 // Sync with SweeperThread's second phase.
 262                 phaser.arriveAndAwaitAdvance();
 263                 System.out.println("AllocatorThread is doing task " + i +
 264                     " phase " + phaser.getPhase());
 265                 doTask();
 266                 // Sync with SweeperThread's first phase.
 267                 phaser.arriveAndAwaitAdvance();
 268                 System.out.println("AllocatorThread done task " + i +
 269                     " phase " + phaser.getPhase());
 270                 if (testFailed) {
 271                     return;
 272                 }
 273             }
 274         }
 275     }
 276 
 277     static class SweeperThread extends Thread {
 278         private void doTask() {
 279             for (; mpool.getUsage().getUsed() >=
 280                        mpool.getUsageThreshold();) {
 281                 // clear all allocated objects and invoke GC
 282                 objectPool.clear();
 283                 mm.gc();
 284                 goSleep(100);
 285             }
 286         }
 287         @Override
 288         public void run() {
 289             for (int i = 1; i <= NUM_TRIGGERS; i++) {
 290                 // Sync with AllocatorThread's first phase.
 291                 phaser.arriveAndAwaitAdvance();
 292                 System.out.println("SweepThread is doing task " + i +
 293                     " phase " + phaser.getPhase());
 294                 doTask();
 295 
 296                 listenerInvoked = false;
 297 
 298                 // Sync with AllocatorThread's second phase.
 299                 phaser.arriveAndAwaitAdvance();
 300                 System.out.println("SweepThread done task " + i +
 301                     " phase " + phaser.getPhase());
 302                 if (testFailed) return;
 303             }
 304         }
 305     }
 306 }