private static void checkGarbageCollectionNotificationInfoContent(
      GarbageCollectionNotificationInfo notif) throws Exception {
    System.out.println("GC notification for " + notif.getGcName());
    System.out.print("Action: " + notif.getGcAction());
    System.out.println(" Cause: " + notif.getGcCause());
    GcInfo info = notif.getGcInfo();
    System.out.print("GC Info #" + info.getId());
    System.out.print(" start:" + info.getStartTime());
    System.out.print(" end:" + info.getEndTime());
    System.out.println(" (" + info.getDuration() + "ms)");
    Map<String, MemoryUsage> usage = info.getMemoryUsageBeforeGc();

    List<String> pnames = new ArrayList<String>();
    for (Map.Entry entry : usage.entrySet()) {
      String poolname = (String) entry.getKey();
      pnames.add(poolname);
      MemoryUsage busage = (MemoryUsage) entry.getValue();
      MemoryUsage ausage = (MemoryUsage) info.getMemoryUsageAfterGc().get(poolname);
      if (ausage == null) {
        throw new RuntimeException("After Gc Memory does not exist" + " for " + poolname);
      }
      System.out.println("Usage for pool " + poolname);
      System.out.println("   Before GC: " + busage);
      System.out.println("   After GC: " + ausage);
    }

    // check if memory usage for all memory pools are returned
    List<MemoryPoolMXBean> pools = ManagementFactory.getMemoryPoolMXBeans();
    for (MemoryPoolMXBean p : pools) {
      if (!pnames.contains(p.getName())) {
        throw new RuntimeException(
            "GcInfo does not contain " + "memory usage for pool " + p.getName());
      }
    }
  }
 public static void main(String[] args) throws Exception {
   MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
   final Boolean isNotificationSupported =
       AccessController.doPrivileged(
           new PrivilegedAction<Boolean>() {
             public Boolean run() {
               try {
                 Class cl = Class.forName("sun.management.VMManagementImpl");
                 Field f = cl.getDeclaredField("gcNotificationSupport");
                 f.setAccessible(true);
                 return f.getBoolean(null);
               } catch (ClassNotFoundException e) {
                 return false;
               } catch (NoSuchFieldException e) {
                 return false;
               } catch (IllegalAccessException e) {
                 return false;
               }
             }
           });
   if (!isNotificationSupported) {
     System.out.println("GC Notification not supported by the JVM, test skipped");
     return;
   }
   final ObjectName gcMXBeanPattern = new ObjectName("java.lang:type=GarbageCollector,*");
   Set<ObjectName> names = mbs.queryNames(gcMXBeanPattern, null);
   if (names.isEmpty()) throw new Exception("Test incorrect: no GC MXBeans");
   number = names.size();
   for (ObjectName n : names) {
     if (mbs.isInstanceOf(n, "javax.management.NotificationEmitter")) {
       listenerInvoked.put(n.getCanonicalName(), null);
       GcListener listener = new GcListener();
       mbs.addNotificationListener(n, listener, null, null);
     }
   }
   // Invocation of System.gc() to trigger major GC
   System.gc();
   // Allocation of many short living and small objects to trigger minor GC
   Object data[] = new Object[32];
   for (int i = 0; i < 100000000; i++) {
     data[i % 32] = new int[8];
   }
   int wakeup = 0;
   synchronized (synchronizer) {
     while (count != number) {
       synchronizer.wait(10000);
       wakeup++;
       if (wakeup > 10) break;
     }
   }
   for (GarbageCollectionNotificationInfo notif : listenerInvoked.values()) {
     checkGarbageCollectionNotificationInfoContent(notif);
   }
   System.out.println("Test passed");
 }
  static class Holder {

    Holder(MongoOptions options) {
      _options = options;
    }

    DBPortPool get(InetSocketAddress addr) {

      DBPortPool p = _pools.get(addr);

      if (p != null) return p;

      synchronized (_pools) {
        p = _pools.get(addr);
        if (p != null) {
          return p;
        }

        p = new DBPortPool(addr, _options);
        _pools.put(addr, p);
        String name = "com.mongodb:type=ConnectionPool,host=" + addr.toString().replace(':', '_');

        try {
          ObjectName on = new ObjectName(name);
          if (_server.isRegistered(on)) {
            _server.unregisterMBean(on);
            Bytes.LOGGER.log(
                Level.INFO, "multiple Mongo instances for same host, jmx numbers might be off");
          }
          _server.registerMBean(p, on);
        } catch (JMException e) {
          Bytes.LOGGER.log(Level.WARNING, "jmx registration error, continuing", e);
        } catch (java.security.AccessControlException e) {
          Bytes.LOGGER.log(Level.WARNING, "jmx registration error, continuing", e);
        }
      }

      return p;
    }

    void close() {
      synchronized (_pools) {
        for (DBPortPool p : _pools.values()) {
          p.close();
        }
      }
    }

    final MongoOptions _options;
    final Map<InetSocketAddress, DBPortPool> _pools =
        Collections.synchronizedMap(new HashMap<InetSocketAddress, DBPortPool>());
    final MBeanServer _server = ManagementFactory.getPlatformMBeanServer();
  }
 private static void checkPlatformMBeans() throws Exception {
   MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
   Set<ObjectName> mbeanNames = mbs.queryNames(null, null);
   for (ObjectName name : mbeanNames) {
     if (!mbs.isInstanceOf(name, NotificationBroadcaster.class.getName())) {
       System.out.println(name + ": not a NotificationBroadcaster");
     } else {
       MBeanInfo mbi = mbs.getMBeanInfo(name);
       check(name.toString(), mbi.getNotifications());
     }
   }
 }
  public static void main(String[] args) throws Exception {
    // TODO Auto-generated method stub
    if (args.length != 4) {
      System.err.println("Please provide process id zabbix-host zabbix-port host-guid");
      System.exit(-1);
    }
    String processPid = args[0];
    String zabbixHost = args[1];
    String zabbixPort = args[2];
    String hostGuid = args[3];

    VirtualMachine vm = VirtualMachine.attach(processPid);
    String connectorAddr =
        vm.getAgentProperties().getProperty("com.sun.management.jmxremote.localConnectorAddress");
    if (connectorAddr == null) {
      String agent =
          vm.getSystemProperties().getProperty("java.home")
              + File.separator
              + "lib"
              + File.separator
              + "management-agent.jar";
      vm.loadAgent(agent);
      connectorAddr =
          vm.getAgentProperties().getProperty("com.sun.management.jmxremote.localConnectorAddress");
    }
    JMXServiceURL serviceURL = new JMXServiceURL(connectorAddr);
    JMXConnector connector = JMXConnectorFactory.connect(serviceURL);
    MBeanServerConnection mbsc = connector.getMBeanServerConnection();
    ObjectName objName = new ObjectName(ManagementFactory.THREAD_MXBEAN_NAME);
    Set<ObjectName> mbeans = mbsc.queryNames(objName, null);
    for (ObjectName name : mbeans) {
      ThreadMXBean threadBean;
      threadBean =
          ManagementFactory.newPlatformMXBeanProxy(mbsc, name.toString(), ThreadMXBean.class);
      long threadIds[] = threadBean.getAllThreadIds();
      for (long threadId : threadIds) {
        ThreadInfo threadInfo = threadBean.getThreadInfo(threadId);
        System.out.println(threadInfo.getThreadName() + " / " + threadInfo.getThreadState());
      }
    }
  }
 public ActiveManagementCoordinator() throws Exception {
   this.mbs = ManagementFactory.getPlatformMBeanServer();
   this.regName = getRegistryName();
 }
Beispiel #7
0
  private void tryConnect(boolean requireRemoteSSL) throws IOException {
    if (jmxUrl == null && "localhost".equals(hostName) && port == 0) {
      // Monitor self
      this.jmxc = null;
      this.mbsc = ManagementFactory.getPlatformMBeanServer();
      this.server = Snapshot.newSnapshot(mbsc);
    } else {
      // Monitor another process
      if (lvm != null) {
        if (!lvm.isManageable()) {
          lvm.startManagementAgent();
          if (!lvm.isManageable()) {
            // FIXME: what to throw
            throw new IOException(lvm + "not manageable");
          }
        }
        if (this.jmxUrl == null) {
          this.jmxUrl = new JMXServiceURL(lvm.connectorAddress());
        }
      }
      Map<String, Object> env = new HashMap<String, Object>();
      if (requireRemoteSSL) {
        env.put("jmx.remote.x.check.stub", "true");
      }
      // Need to pass in credentials ?
      if (userName == null && password == null) {
        if (isVmConnector()) {
          // Check for SSL config on reconnection only
          if (stub == null) {
            checkSslConfig();
          }
          this.jmxc = new RMIConnector(stub, null);
          jmxc.connect(env);
        } else {
          this.jmxc = JMXConnectorFactory.connect(jmxUrl, env);
        }
      } else {
        env.put(JMXConnector.CREDENTIALS, new String[] {userName, password});
        if (isVmConnector()) {
          // Check for SSL config on reconnection only
          if (stub == null) {
            checkSslConfig();
          }
          this.jmxc = new RMIConnector(stub, null);
          jmxc.connect(env);
        } else {
          this.jmxc = JMXConnectorFactory.connect(jmxUrl, env);
        }
      }
      this.mbsc = jmxc.getMBeanServerConnection();
      this.server = Snapshot.newSnapshot(mbsc);
    }
    this.isDead = false;

    try {
      ObjectName on = new ObjectName(THREAD_MXBEAN_NAME);
      this.hasPlatformMXBeans = server.isRegistered(on);
      this.hasHotSpotDiagnosticMXBean =
          server.isRegistered(new ObjectName(HOTSPOT_DIAGNOSTIC_MXBEAN_NAME));
      // check if it has 6.0 new APIs
      if (this.hasPlatformMXBeans) {
        MBeanOperationInfo[] mopis = server.getMBeanInfo(on).getOperations();
        // look for findDeadlockedThreads operations;
        for (MBeanOperationInfo op : mopis) {
          if (op.getName().equals("findDeadlockedThreads")) {
            this.supportsLockUsage = true;
            break;
          }
        }

        on = new ObjectName(COMPILATION_MXBEAN_NAME);
        this.hasCompilationMXBean = server.isRegistered(on);
      }
    } catch (MalformedObjectNameException e) {
      // should not reach here
      throw new InternalError(e.getMessage());
    } catch (IntrospectionException e) {
      InternalError ie = new InternalError(e.getMessage());
      ie.initCause(e);
      throw ie;
    } catch (InstanceNotFoundException e) {
      InternalError ie = new InternalError(e.getMessage());
      ie.initCause(e);
      throw ie;
    } catch (ReflectionException e) {
      InternalError ie = new InternalError(e.getMessage());
      ie.initCause(e);
      throw ie;
    }

    if (hasPlatformMXBeans) {
      // WORKAROUND for bug 5056632
      // Check if the access role is correct by getting a RuntimeMXBean
      getRuntimeMXBean();
    }
  }
 public ActiveManagementCoordinator() throws Exception {
   this.mbs = ManagementFactory.getPlatformMBeanServer();
 }
public class ThreadMXBeanProxy {
  private static MBeanServer server = ManagementFactory.getPlatformMBeanServer();
  private static ThreadMXBean mbean;
  static Mutex mutex = new Mutex();
  static Object lock = new Object();
  static MyThread thread = new MyThread();

  public static void main(String[] argv) throws Exception {
    mbean = newPlatformMXBeanProxy(server, THREAD_MXBEAN_NAME, ThreadMXBean.class);

    if (!mbean.isSynchronizerUsageSupported()) {
      System.out.println("Monitoring of synchronizer usage not supported");
      return;
    }

    thread.setDaemon(true);
    thread.start();

    // wait until myThread acquires mutex and lock owner is set.
    while (!(mutex.isLocked() && mutex.getLockOwner() == thread)) {
      try {
        Thread.sleep(100);
      } catch (InterruptedException e) {
        throw new RuntimeException(e);
      }
    }

    long[] ids = new long[] {thread.getId()};

    // validate the local access
    ThreadInfo[] infos = getThreadMXBean().getThreadInfo(ids, true, true);
    if (infos.length != 1) {
      throw new RuntimeException(
          "Returned ThreadInfo[] of length=" + infos.length + ". Expected to be 1.");
    }
    thread.checkThreadInfo(infos[0]);

    // validate the remote access
    infos = mbean.getThreadInfo(ids, true, true);
    if (infos.length != 1) {
      throw new RuntimeException(
          "Returned ThreadInfo[] of length=" + infos.length + ". Expected to be 1.");
    }
    thread.checkThreadInfo(infos[0]);

    boolean found = false;
    infos = mbean.dumpAllThreads(true, true);
    for (ThreadInfo ti : infos) {
      if (ti.getThreadId() == thread.getId()) {
        thread.checkThreadInfo(ti);
        found = true;
      }
    }

    if (!found) {
      throw new RuntimeException("No ThreadInfo found for MyThread");
    }

    System.out.println("Test passed");
  }

  static class MyThread extends Thread {
    public MyThread() {
      super("MyThread");
    }

    public void run() {
      synchronized (lock) {
        mutex.lock();
        Object o = new Object();
        synchronized (o) {
          try {
            o.wait();
          } catch (InterruptedException e) {
            throw new RuntimeException(e);
          }
        }
      }
    }

    int OWNED_MONITORS = 1;
    int OWNED_SYNCS = 1;

    void checkThreadInfo(ThreadInfo info) {
      if (!getName().equals(info.getThreadName())) {
        throw new RuntimeException(
            "Name: " + info.getThreadName() + " not matched. Expected: " + getName());
      }

      MonitorInfo[] monitors = info.getLockedMonitors();
      if (monitors.length != OWNED_MONITORS) {
        throw new RuntimeException(
            "Number of locked monitors = "
                + monitors.length
                + " not matched. Expected: "
                + OWNED_MONITORS);
      }
      MonitorInfo m = monitors[0];
      StackTraceElement ste = m.getLockedStackFrame();
      int depth = m.getLockedStackDepth();
      StackTraceElement[] stacktrace = info.getStackTrace();
      if (!ste.equals(stacktrace[depth])) {
        System.out.println("LockedStackFrame:- " + ste);
        System.out.println("StackTrace at " + depth + " :-" + stacktrace[depth]);
        throw new RuntimeException(
            "LockedStackFrame does not match " + "stack frame in ThreadInfo.getStackTrace");
      }

      String className = lock.getClass().getName();
      int hcode = System.identityHashCode(lock);
      if (!className.equals(m.getClassName())
          || hcode != m.getIdentityHashCode()
          || !m.getLockedStackFrame().getMethodName().equals("run")) {
        System.out.println(info);
        throw new RuntimeException("MonitorInfo " + m + " doesn't match.");
      }

      LockInfo[] syncs = info.getLockedSynchronizers();
      if (syncs.length != OWNED_SYNCS) {
        throw new RuntimeException(
            "Number of locked syncs = " + syncs.length + " not matched. Expected: " + OWNED_SYNCS);
      }
      AbstractOwnableSynchronizer s = mutex.getSync();
      String lockName = s.getClass().getName();
      hcode = System.identityHashCode(s);
      if (!lockName.equals(syncs[0].getClassName())) {
        throw new RuntimeException(
            "LockInfo : " + syncs[0] + " class name not matched. Expected: " + lockName);
      }
      if (hcode != syncs[0].getIdentityHashCode()) {
        throw new RuntimeException(
            "LockInfo: " + syncs[0] + " IdentityHashCode not matched. Expected: " + hcode);
      }
      LockInfo li = info.getLockInfo();
      if (li == null) {
        throw new RuntimeException("Expected non-null LockInfo");
      }
    }
  }

  static class Mutex implements Lock, java.io.Serializable {

    // Our internal helper class
    class Sync extends AbstractQueuedSynchronizer {
      // Report whether in locked state
      protected boolean isHeldExclusively() {
        return getState() == 1;
      }

      // Acquire the lock if state is zero
      public boolean tryAcquire(int acquires) {
        assert acquires == 1; // Otherwise unused
        if (compareAndSetState(0, 1)) {
          setExclusiveOwnerThread(Thread.currentThread());
          return true;
        }
        return false;
      }

      // Release the lock by setting state to zero
      protected boolean tryRelease(int releases) {
        assert releases == 1; // Otherwise unused
        if (getState() == 0) throw new IllegalMonitorStateException();
        setExclusiveOwnerThread(null);
        setState(0);
        return true;
      }

      // Provide a Condition
      Condition newCondition() {
        return new ConditionObject();
      }

      // Deserialize properly
      private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException {
        s.defaultReadObject();
        setState(0); // reset to unlocked state
      }

      protected Thread getLockOwner() {
        return getExclusiveOwnerThread();
      }
    }

    // The sync object does all the hard work. We just forward to it.
    private final Sync sync = new Sync();

    public void lock() {
      sync.acquire(1);
    }

    public boolean tryLock() {
      return sync.tryAcquire(1);
    }

    public void unlock() {
      sync.release(1);
    }

    public Condition newCondition() {
      return sync.newCondition();
    }

    public boolean isLocked() {
      return sync.isHeldExclusively();
    }

    public boolean hasQueuedThreads() {
      return sync.hasQueuedThreads();
    }

    public void lockInterruptibly() throws InterruptedException {
      sync.acquireInterruptibly(1);
    }

    public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException {
      return sync.tryAcquireNanos(1, unit.toNanos(timeout));
    }

    public Thread getLockOwner() {
      return sync.getLockOwner();
    }

    public AbstractOwnableSynchronizer getSync() {
      return sync;
    }
  }
}
Beispiel #10
0
public class ValidateOpenTypes {
  private static MBeanServer server = ManagementFactory.getPlatformMBeanServer();
  private static ObjectName memory;
  private static ObjectName thread;
  private static ObjectName runtime;
  private static ObjectName os;
  private static ObjectName heapPool = null;
  private static ObjectName nonHeapPool = null;

  public static void main(String[] argv) throws Exception {
    memory = new ObjectName(MEMORY_MXBEAN_NAME);
    runtime = new ObjectName(RUNTIME_MXBEAN_NAME);
    thread = new ObjectName(THREAD_MXBEAN_NAME);
    os = new ObjectName(OPERATING_SYSTEM_MXBEAN_NAME);

    List<MemoryPoolMXBean> pools = getMemoryPoolMXBeans();
    for (MemoryPoolMXBean p : pools) {
      if (heapPool == null
          && p.getType() == MemoryType.HEAP
          && p.isUsageThresholdSupported()
          && p.isCollectionUsageThresholdSupported()) {
        heapPool = new ObjectName(MEMORY_POOL_MXBEAN_DOMAIN_TYPE + ",name=" + p.getName());
      }
      if (nonHeapPool == null
          && p.getType() == MemoryType.NON_HEAP
          && p.isUsageThresholdSupported()) {
        nonHeapPool = new ObjectName(MEMORY_POOL_MXBEAN_DOMAIN_TYPE + ",name=" + p.getName());
      }
    }

    // Check notification emitters
    MyListener listener = new MyListener();
    server.addNotificationListener(memory, listener, null, null);
    server.removeNotificationListener(memory, listener);

    checkEnum();
    checkList();
    checkMap();
    checkMemoryUsage();
    checkThreadInfo();

    checkOS();
    checkSunGC();

    System.out.println("Test passed.");
  }

  private static void checkEnum() throws Exception {
    String type = (String) server.getAttribute(heapPool, "Type");
    if (!type.equals("HEAP")) {
      throw new RuntimeException("TEST FAILED: " + " incorrect memory type for " + heapPool);
    }

    type = (String) server.getAttribute(nonHeapPool, "Type");
    if (!type.equals("NON_HEAP")) {
      throw new RuntimeException("TEST FAILED: " + " incorrect memory type for " + nonHeapPool);
    }
  }

  private static final String OPTION = "-verbose:gc";

  private static void checkList() throws Exception {
    String[] args = (String[]) server.getAttribute(runtime, "InputArguments");
    if (args.length < 1) {
      throw new RuntimeException("TEST FAILED: " + " empty input arguments");
    }
    // check if -verbose:gc exists
    boolean found = false;
    for (String option : args) {
      if (option.equals(OPTION)) {
        found = true;
        break;
      }
    }
    if (!found) {
      throw new RuntimeException("TEST FAILED: " + "VM option " + OPTION + " not found");
    }
  }

  private static final String KEY1 = "test.property.key1";
  private static final String VALUE1 = "test.property.value1";
  private static final String KEY2 = "test.property.key2";
  private static final String VALUE2 = "test.property.value2";
  private static final String KEY3 = "test.property.key3";

  private static void checkMap() throws Exception {
    // Add new system properties
    System.setProperty(KEY1, VALUE1);
    System.setProperty(KEY2, VALUE2);

    TabularData props1 = (TabularData) server.getAttribute(runtime, "SystemProperties");

    String value1 = getProperty(props1, KEY1);
    if (value1 == null || !value1.equals(VALUE1)) {
      throw new RuntimeException(
          "TEST FAILED: "
              + KEY1
              + " property found"
              + " with value = "
              + value1
              + " but expected to be "
              + VALUE1);
    }

    String value2 = getProperty(props1, KEY2);
    if (value2 == null || !value2.equals(VALUE2)) {
      throw new RuntimeException(
          "TEST FAILED: "
              + KEY2
              + " property found"
              + " with value = "
              + value2
              + " but expected to be "
              + VALUE2);
    }

    String value3 = getProperty(props1, KEY3);
    if (value3 != null) {
      throw new RuntimeException(
          "TEST FAILED: " + KEY3 + " property found" + " but should not exist");
    }
  }

  private static String getProperty(TabularData td, String propName) {
    CompositeData cd = td.get(new Object[] {propName});
    if (cd != null) {
      String key = (String) cd.get("key");
      if (!propName.equals(key)) {
        throw new RuntimeException(
            "TEST FAILED: " + key + " property found" + " but expected to be " + propName);
      }
      return (String) cd.get("value");
    }
    return null;
  }

  private static void checkMemoryUsage() throws Exception {
    // sanity check to have non-zero usage
    Object u1 = server.getAttribute(memory, "HeapMemoryUsage");
    Object u2 = server.getAttribute(memory, "NonHeapMemoryUsage");
    Object u3 = server.getAttribute(heapPool, "Usage");
    Object u4 = server.getAttribute(nonHeapPool, "Usage");
    if (getCommitted(u1) <= 0
        || getCommitted(u2) <= 0
        || getCommitted(u3) <= 0
        || getCommitted(u4) <= 0) {
      throw new RuntimeException("TEST FAILED: " + " expected non-zero committed usage");
    }
    server.invoke(memory, "gc", new Object[0], new String[0]);
    Object u5 = server.getAttribute(heapPool, "CollectionUsage");
    if (getCommitted(u5) <= 0) {
      throw new RuntimeException("TEST FAILED: " + " expected non-zero committed collected usage");
    }
  }

  private static long getCommitted(Object data) {
    MemoryUsage u = MemoryUsage.from((CompositeData) data);
    return u.getCommitted();
  }

  private static void checkThreadInfo() throws Exception {
    // assume all threads stay alive
    long[] ids = (long[]) server.getAttribute(thread, "AllThreadIds");
    Object result = server.invoke(thread, "getThreadInfo", new Object[] {ids}, new String[] {"[J"});
    for (CompositeData cd : (CompositeData[]) result) {
      printThreadInfo(cd);
    }

    result =
        server.invoke(
            thread,
            "getThreadInfo",
            new Object[] {ids, new Integer(2)},
            new String[] {"[J", "int"});
    for (CompositeData cd : (CompositeData[]) result) {
      printThreadInfo(cd);
    }

    long id = Thread.currentThread().getId();
    result =
        server.invoke(thread, "getThreadInfo", new Object[] {new Long(id)}, new String[] {"long"});
    printThreadInfo((CompositeData) result);

    result =
        server.invoke(
            thread,
            "getThreadInfo",
            new Object[] {new Long(id), new Integer(2)},
            new String[] {"long", "int"});
    printThreadInfo((CompositeData) result);
  }

  private static void printThreadInfo(CompositeData cd) {
    ThreadInfo info = ThreadInfo.from(cd);
    if (info == null) {
      throw new RuntimeException("TEST FAILED: " + " Null ThreadInfo");
    }

    System.out.print(info.getThreadName());
    System.out.print(" id=" + info.getThreadId());
    System.out.println(" " + info.getThreadState());

    for (StackTraceElement s : info.getStackTrace()) {
      System.out.println(s);
    }
  }

  private static void checkOS() throws Exception {
    Integer cpus = (Integer) server.getAttribute(os, "AvailableProcessors");
    System.out.println("# CPUs = " + cpus);
    Long vmem = (Long) server.getAttribute(os, "CommittedVirtualMemorySize");
    System.out.println("Committed virtual memory = " + vmem);
  }

  private static void checkSunGC() throws Exception {
    // Test com.sun.management proxy
    List<GarbageCollectorMXBean> gcs = getGarbageCollectorMXBeans();
    for (GarbageCollectorMXBean gc : gcs) {
      ObjectName sunGc =
          new ObjectName(GARBAGE_COLLECTOR_MXBEAN_DOMAIN_TYPE + ",name=" + gc.getName());
      CompositeData cd = (CompositeData) server.getAttribute(sunGc, "LastGcInfo");
      if (cd != null) {
        System.out.println("GC statistic for : " + gc.getName());
        printGcInfo(cd);
      }
    }
  }

  private static void printGcInfo(CompositeData cd) throws Exception {
    GcInfo info = GcInfo.from(cd);
    System.out.print("GC #" + info.getId());
    System.out.print(" start:" + info.getStartTime());
    System.out.print(" end:" + info.getEndTime());
    System.out.println(" (" + info.getDuration() + "ms)");
    Map<String, MemoryUsage> usage = info.getMemoryUsageBeforeGc();

    for (Map.Entry<String, MemoryUsage> entry : usage.entrySet()) {
      String poolname = entry.getKey();
      MemoryUsage busage = entry.getValue();
      MemoryUsage ausage = info.getMemoryUsageAfterGc().get(poolname);
      if (ausage == null) {
        throw new RuntimeException("After Gc Memory does not exist" + " for " + poolname);
      }
      System.out.println("Usage for pool " + poolname);
      System.out.println("   Before GC: " + busage);
      System.out.println("   After GC: " + ausage);
    }
  }

  static class MyListener implements NotificationListener {
    public void handleNotification(Notification notif, Object handback) {
      return;
    }
  }
}