1 /*
   2  * Copyright (c) 2011, 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     7036199
  27  * @summary Check that GarbageCollectionNotification contents are reasonable
  28  * @author  Frederic Parain
  29  * @requires vm.opt.ExplicitGCInvokesConcurrent == null | vm.opt.ExplicitGCInvokesConcurrent == false
  30  * @run     main/othervm GarbageCollectionNotificationContentTest
  31  */
  32 
  33 import java.util.*;
  34 import java.lang.management.*;
  35 import java.lang.reflect.*;
  36 import javax.management.*;
  37 import javax.management.openmbean.*;
  38 import com.sun.management.GarbageCollectionNotificationInfo;
  39 import com.sun.management.GcInfo;
  40 import java.security.AccessController;
  41 import java.security.PrivilegedAction;
  42 import java.lang.reflect.Field;
  43 
  44 public class GarbageCollectionNotificationContentTest {
  45     private static HashMap<String,GarbageCollectionNotificationInfo> listenerInvoked
  46         = new HashMap<String,GarbageCollectionNotificationInfo>();
  47     static volatile long count = 0;
  48     static volatile long number = 0;
  49     static Object synchronizer = new Object();
  50 
  51     static class GcListener implements NotificationListener {
  52         public void handleNotification(Notification notif, Object handback) {
  53             String type = notif.getType();
  54             if (type.equals(GarbageCollectionNotificationInfo.GARBAGE_COLLECTION_NOTIFICATION)) {
  55                 GarbageCollectionNotificationInfo gcNotif =
  56                     GarbageCollectionNotificationInfo.from((CompositeData) notif.getUserData());
  57                 String source = ((ObjectName)notif.getSource()).getCanonicalName();
  58                 synchronized(synchronizer) {
  59                     if(listenerInvoked.get(source) == null) {
  60                             listenerInvoked.put(((ObjectName)notif.getSource()).getCanonicalName(),gcNotif);
  61                             count++;
  62                             if(count >= number) {
  63                                 synchronizer.notify();
  64                             }
  65                     }
  66                 }
  67             }
  68         }
  69     }
  70 
  71     public static void main(String[] args) throws Exception {
  72         MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
  73         final Boolean isNotificationSupported = AccessController.doPrivileged (new PrivilegedAction<Boolean>() {
  74                 public Boolean run() {
  75                     try {
  76                         Class cl = Class.forName("sun.management.VMManagementImpl");
  77                         Field f = cl.getDeclaredField("gcNotificationSupport");
  78                         f.setAccessible(true);
  79                         return f.getBoolean(null);
  80                     } catch(ClassNotFoundException e) {
  81                         return false;
  82                     } catch(NoSuchFieldException e) {
  83                         return false;
  84                     } catch(IllegalAccessException e) {
  85                         return false;
  86                     }
  87                 }
  88             });
  89         if(!isNotificationSupported) {
  90             System.out.println("GC Notification not supported by the JVM, test skipped");
  91             return;
  92         }
  93         final ObjectName gcMXBeanPattern =
  94                 new ObjectName("java.lang:type=GarbageCollector,*");
  95         Set<ObjectName> names =
  96                 mbs.queryNames(gcMXBeanPattern, null);
  97         if (names.isEmpty())
  98             throw new Exception("Test incorrect: no GC MXBeans");
  99         number = names.size();
 100         for (ObjectName n : names) {
 101             if(mbs.isInstanceOf(n,"javax.management.NotificationEmitter")) {
 102                 listenerInvoked.put(n.getCanonicalName(),null);
 103                 GcListener listener = new GcListener();
 104                 mbs.addNotificationListener(n, listener, null, null);
 105             }
 106         }
 107         // Invocation of System.gc() to trigger major GC
 108         System.gc();
 109         // Allocation of many short living and small objects to trigger minor GC
 110         Object data[] = new Object[32];
 111         for(int i = 0; i<100000000; i++) {
 112             data[i%32] = new int[8];
 113         }
 114         int wakeup = 0;
 115         synchronized(synchronizer) {
 116             while(count != number) {
 117                 synchronizer.wait(10000);
 118                 wakeup++;
 119                 if(wakeup > 10)
 120                     break;
 121             }
 122         }
 123         for (GarbageCollectionNotificationInfo notif : listenerInvoked.values() ) {
 124             checkGarbageCollectionNotificationInfoContent(notif);
 125         }
 126         System.out.println("Test passed");
 127     }
 128 
 129     private static void checkGarbageCollectionNotificationInfoContent(GarbageCollectionNotificationInfo notif) throws Exception {
 130         System.out.println("GC notification for "+notif.getGcName());
 131         System.out.print("Action: "+notif.getGcAction());
 132         System.out.println(" Cause: "+notif.getGcCause());
 133         GcInfo info = notif.getGcInfo();
 134         System.out.print("GC Info #" + info.getId());
 135         System.out.print(" start:" + info.getStartTime());
 136         System.out.print(" end:" + info.getEndTime());
 137         System.out.println(" (" + info.getDuration() + "ms)");
 138         Map<String, MemoryUsage> usage = info.getMemoryUsageBeforeGc();
 139 
 140         List<String> pnames = new ArrayList<String>();
 141         for (Map.Entry entry : usage.entrySet() ) {
 142             String poolname = (String) entry.getKey();
 143             pnames.add(poolname);
 144             MemoryUsage busage = (MemoryUsage) entry.getValue();
 145             MemoryUsage ausage = (MemoryUsage) info.getMemoryUsageAfterGc().get(poolname);
 146             if (ausage == null) {
 147                 throw new RuntimeException("After Gc Memory does not exist" +
 148                     " for " + poolname);
 149             }
 150             System.out.println("Usage for pool " + poolname);
 151             System.out.println("   Before GC: " + busage);
 152             System.out.println("   After GC: " + ausage);
 153         }
 154 
 155         // check if memory usage for all memory pools are returned
 156         List<MemoryPoolMXBean> pools = ManagementFactory.getMemoryPoolMXBeans();
 157         for (MemoryPoolMXBean p : pools ) {
 158             if (!pnames.contains(p.getName())) {
 159                 throw new RuntimeException("GcInfo does not contain " +
 160                     "memory usage for pool " + p.getName());
 161             }
 162         }
 163     }
 164 }