1 /*
   2  * Copyright (c) 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 TestOldGenCollectionUsage.java
  26  * @bug 8195115
  27  * @summary G1 Old Gen's CollectionUsage.used is zero after mixed GC which is incorrect
  28  * @key gc
  29  * @requires vm.gc=="null" | vm.gc=="G1"
  30  * @library /testlibrary /testlibrary/whitebox
  31  * @build ClassFileInstaller com.oracle.java.testlibrary.* sun.hotspot.WhiteBox TestOldGenCollectionUsage
  32  * @run main ClassFileInstaller sun.hotspot.WhiteBox
  33  *                              sun.hotspot.WhiteBox$WhiteBoxPermission
  34  * @run main/othervm -Xbootclasspath/a:. -XX:+UseG1GC -XX:+UnlockExperimentalVMOptions -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI -verbose:gc -XX:SurvivorRatio=1 -Xmx14m -Xms14m -XX:MaxTenuringThreshold=1 -XX:InitiatingHeapOccupancyPercent=100 -XX:G1MixedGCCountTarget=4 -XX:MaxGCPauseMillis=30000 -XX:G1HeapRegionSize=1m -XX:G1HeapWastePercent=0 -XX:G1MixedGCLiveThresholdPercent=100 TestOldGenCollectionUsage
  35  */
  36 
  37 import com.oracle.java.testlibrary.Asserts;
  38 import sun.hotspot.WhiteBox;
  39 
  40 import java.util.ArrayList;
  41 import java.util.List;
  42 import java.util.Collections;
  43 
  44 import java.lang.management.*;
  45 
  46 // 8195115 says that for the "G1 Old Gen" MemoryPool, CollectionUsage.used
  47 // is zero for G1 after a mixed collection, which is incorrect.
  48 
  49 public class TestOldGenCollectionUsage {
  50 
  51     private String poolName = "G1 Old Gen";
  52     private String collectorName = "G1 Young Generation";
  53 
  54     public static void main(String [] args) throws Exception {
  55         TestOldGenCollectionUsage t = new TestOldGenCollectionUsage();
  56         t.run();
  57     }
  58 
  59     public TestOldGenCollectionUsage() {
  60         System.out.println("Monitor G1 Old Gen pool with G1 Young Generation collector.");
  61     }
  62 
  63     public void run() {
  64         // Find memory pool and collector
  65         List<MemoryPoolMXBean> pools = ManagementFactory.getMemoryPoolMXBeans();
  66         MemoryPoolMXBean pool = null;
  67         boolean foundPool = false;
  68         for (int i = 0; i < pools.size(); i++) {
  69             pool = pools.get(i);
  70             String name = pool.getName();
  71             if (name.contains(poolName)) {
  72                 System.out.println("Found pool: " + name);
  73                 foundPool = true;
  74                 break;
  75             }
  76         }
  77         if (!foundPool) {
  78             throw new RuntimeException(poolName + " not found, test with -XX:+UseG1GC");
  79         }
  80 
  81         List<GarbageCollectorMXBean> collectors = ManagementFactory.getGarbageCollectorMXBeans();
  82         GarbageCollectorMXBean collector = null;
  83         boolean foundCollector = false;
  84         for (int i = 0; i < collectors.size(); i++) {
  85             collector = collectors.get(i);
  86             String name = collector.getName();
  87             if (name.contains(collectorName)) {
  88                 System.out.println("Found collector: " + name);
  89                 foundCollector = true;
  90                 break;
  91             }
  92         }
  93         if (!foundCollector) {
  94             throw new RuntimeException(collectorName + " not found, test with -XX:+UseG1GC");
  95         }
  96 
  97         MixedGCProvoker gcProvoker = new MixedGCProvoker();
  98         gcProvoker.allocateOldObjects();
  99 
 100         // Verify no non-zero result was stored
 101         long usage = pool.getCollectionUsage().getUsed();
 102         System.out.println(poolName + ": usage after GC = " + usage);
 103         if (usage > 0) {
 104             throw new RuntimeException("Premature mixed collections(s)");
 105         }
 106 
 107         // Verify that collections were done
 108         long collectionCount = collector.getCollectionCount();
 109         System.out.println(collectorName + ": collection count = "
 110                            + collectionCount);
 111         long collectionTime = collector.getCollectionTime();
 112         System.out.println(collectorName + ": collection time  = "
 113                            + collectionTime);
 114         if (collectionCount <= 0) {
 115             throw new RuntimeException("Collection count <= 0");
 116         }
 117         if (collectionTime <= 0) {
 118             throw new RuntimeException("Collector has not run");
 119         }
 120 
 121         gcProvoker.provokeMixedGC();
 122 
 123         usage = pool.getCollectionUsage().getUsed();
 124         System.out.println(poolName + ": usage after GC = " + usage);
 125         if (usage <= 0) {
 126             throw new RuntimeException(poolName + " found with zero usage");
 127         }
 128 
 129         long newCollectionCount = collector.getCollectionCount();
 130         System.out.println(collectorName + ": collection count = "
 131                            + newCollectionCount);
 132         long newCollectionTime = collector.getCollectionTime();
 133         System.out.println(collectorName + ": collection time  = "
 134                            + newCollectionTime);
 135         if (newCollectionCount <= collectionCount) {
 136             throw new RuntimeException("No new collection");
 137         }
 138         if (newCollectionTime <= collectionTime) {
 139             throw new RuntimeException("Collector has not run some more");
 140         }
 141 
 142         System.out.println("Test passed.");
 143     }
 144 
 145     /**
 146      * Utility class to guarantee a mixed GC. The class allocates several arrays and
 147      * promotes them to the oldgen. After that it tries to provoke mixed GC by
 148      * allocating new objects.
 149      *
 150      * The necessary condition for guaranteed mixed GC is running MixedGCProvoker is
 151      * running in VM with the following flags: -XX:MaxTenuringThreshold=1 -Xms12M
 152      * -Xmx12M -XX:G1MixedGCLiveThresholdPercent=100 -XX:G1HeapWastePercent=0
 153      * -XX:G1HeapRegionSize=1m
 154      */
 155     public class MixedGCProvoker {
 156         private final WhiteBox WB = WhiteBox.getWhiteBox();
 157         private final List<byte[]> liveOldObjects = new ArrayList<>();
 158         private final List<byte[]> newObjects = new ArrayList<>();
 159 
 160         public static final int ALLOCATION_SIZE = 20000;
 161         public static final int ALLOCATION_COUNT = 15;
 162 
 163         public void allocateOldObjects() {
 164             List<byte[]> deadOldObjects = new ArrayList<>();
 165             // Allocates buffer and promotes it to the old gen. Mix live and dead old
 166             // objects
 167             for (int i = 0; i < ALLOCATION_COUNT; ++i) {
 168                 liveOldObjects.add(new byte[ALLOCATION_SIZE * 5]);
 169                 deadOldObjects.add(new byte[ALLOCATION_SIZE * 5]);
 170             }
 171 
 172             // Do two young collections, MaxTenuringThreshold=1 will force promotion.
 173             // G1HeapRegionSize=1m guarantees that old gen regions will be filled.
 174             WB.youngGC();
 175             WB.youngGC();
 176             // Check it is promoted & keep alive
 177             Asserts.assertTrue(WB.isObjectInOldGen(liveOldObjects),
 178                                "List of the objects is suppose to be in OldGen");
 179             Asserts.assertTrue(WB.isObjectInOldGen(deadOldObjects),
 180                                "List of the objects is suppose to be in OldGen");
 181         }
 182 
 183         /**
 184          * Waits until Concurent Mark Cycle finishes
 185          * @param wb  Whitebox instance
 186          * @param sleepTime sleep time
 187          */
 188         private void waitTillCMCFinished(int sleepTime) {
 189             while (WB.g1InConcurrentMark()) {
 190                 if (sleepTime > -1) {
 191                     try {
 192                         Thread.sleep(sleepTime);
 193                     } catch (InterruptedException e) {
 194                         System.out.println("Got InterruptedException while waiting for ConcMarkCycle to finish");
 195                     }
 196                 }
 197             }
 198         }
 199 
 200         public void provokeMixedGC() {
 201             waitTillCMCFinished(0);
 202             WB.g1StartConcMarkCycle();
 203             waitTillCMCFinished(0);
 204             WB.youngGC();
 205 
 206             System.out.println("Allocating new objects to provoke mixed GC");
 207             // Provoke a mixed collection. G1MixedGCLiveThresholdPercent=100
 208             // guarantees that full old gen regions will be included.
 209             for (int i = 0; i < (ALLOCATION_COUNT * 20); i++) {
 210                 try {
 211                     newObjects.add(new byte[ALLOCATION_SIZE]);
 212                 } catch (OutOfMemoryError e) {
 213                     newObjects.clear();
 214                     WB.youngGC();
 215                     WB.youngGC();
 216                     System.out.println("OutOfMemoryError is reported, stop allocating new objects");
 217                     break;
 218                 }
 219             }
 220             // check that liveOldObjects still alive
 221             Asserts.assertTrue(WB.isObjectInOldGen(liveOldObjects),
 222                                "List of the objects is suppose to be in OldGen");
 223         }
 224 
 225     }
 226 
 227 }