Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package com.yammer.metrics.core;
  
  import javax.management.*;
 import java.util.*;
A collection of Java Virtual Machine metrics.
 
 public class VirtualMachineMetrics {
     private static final int MAX_STACK_TRACE_DEPTH = 100;
 
     private static final VirtualMachineMetrics INSTANCE = new VirtualMachineMetrics(
             ManagementFactory.getMemoryMXBean(),
             ManagementFactory.getMemoryPoolMXBeans(),
             ManagementFactory.getOperatingSystemMXBean(),
             ManagementFactory.getThreadMXBean(),
             ManagementFactory.getGarbageCollectorMXBeans(),
             ManagementFactory.getRuntimeMXBean(),
             ManagementFactory.getPlatformMBeanServer());

    
The default instance of VirtualMachineMetrics.

Returns:
the default instance
 
     public static VirtualMachineMetrics getInstance() {
         return ;
     }

    
Per-GC statistics.
 
     public static class GarbageCollectorStats {
         private final long runstimeMS;
 
         private GarbageCollectorStats(long runslong timeMS) {
             this. = runs;
             this. = timeMS;
         }

        
Returns the number of times the garbage collector has run.

Returns:
the number of times the garbage collector has run
 
         public long getRuns() {
             return ;
         }

        
Returns the amount of time in the given unit the garbage collector has taken in total.

Parameters:
unit the time unit for the return value
Returns:
the amount of time in the given unit the garbage collector
 
         public long getTime(TimeUnit unit) {
             return unit.convert(.);
         }
     }

    
The management interface for a buffer pool, for example a pool of java.nio.ByteBuffer.allocateDirect(int) or mapped buffers.
 
     public static class BufferPoolStats {
         private final long countmemoryUsedtotalCapacity;
 
         private BufferPoolStats(long countlong memoryUsedlong totalCapacity) {
             this. = count;
             this. = memoryUsed;
             this. = totalCapacity;
         }

        
Returns an estimate of the number of buffers in the pool.

Returns:
An estimate of the number of buffers in this pool
 
         public long getCount() {
             return ;
         }

        
Returns an estimate of the memory that the Java virtual machine is using for this buffer pool. The value returned by this method may differ from the estimate of the total getTotalCapacity() of the buffers in this pool. This difference is explained by alignment, memory allocator, and other implementation specific reasons.

Returns:
An estimate of the memory that the Java virtual machine is using for this buffer pool in bytes, or -1L if an estimate of the memory usage is not available
        public long getMemoryUsed() {
            return ;
        }

        
Returns an estimate of the total capacity of the buffers in this pool. A buffer's capacity is the number of elements it contains and the value returned by this method is an estimate of the total capacity of buffers in the pool in bytes.

Returns:
An estimate of the total capacity of the buffers in this pool in bytes
        public long getTotalCapacity() {
            return ;
        }
    }
    private final MemoryMXBean memory;
    private final List<MemoryPoolMXBeanmemoryPools;
    private final OperatingSystemMXBean os;
    private final ThreadMXBean threads;
    private final RuntimeMXBean runtime;
    private final MBeanServer mBeanServer;
                          List<MemoryPoolMXBeanmemoryPools,
                          OperatingSystemMXBean os,
                          ThreadMXBean threads,
                          List<GarbageCollectorMXBeangarbageCollectors,
                          RuntimeMXBean runtimeMBeanServer mBeanServer) {
        this. = memory;
        this. = memoryPools;
        this. = os;
        this. = threads;
        this. = garbageCollectors;
        this. = runtime;
        this. = mBeanServer;
    }

    
Returns the total initial memory of the current JVM.

Returns:
total Heap and non-heap initial JVM memory in bytes.
    public double totalInit() {
        return .getHeapMemoryUsage().getInit() +
                .getNonHeapMemoryUsage().getInit();
    }

    
Returns the total memory currently used by the current JVM.

Returns:
total Heap and non-heap memory currently used by JVM in bytes.
    public double totalUsed() {
        return .getHeapMemoryUsage().getUsed() +
                .getNonHeapMemoryUsage().getUsed();
    }

    
Returns the total memory currently used by the current JVM.

Returns:
total Heap and non-heap memory currently used by JVM in bytes.
    public double totalMax() {
        return .getHeapMemoryUsage().getMax() +
                .getNonHeapMemoryUsage().getMax();
    }
    
Returns the total memory committed to the JVM.

Returns:
total Heap and non-heap memory currently committed to the JVM in bytes.
    public double totalCommitted() {
        return .getHeapMemoryUsage().getCommitted() +
                .getNonHeapMemoryUsage().getCommitted();
    }
    
Returns the heap initial memory of the current JVM.

Returns:
Heap initial JVM memory in bytes.
    public double heapInit() {
        return .getHeapMemoryUsage().getInit();
    }
    
Returns the heap memory currently used by the current JVM.

Returns:
Heap memory currently used by JVM in bytes.
    public double heapUsed() {
        return .getHeapMemoryUsage().getUsed();
    }
    
Returns the heap memory currently used by the current JVM.

Returns:
Heap memory currently used by JVM in bytes.
    public double heapMax() {
        return .getHeapMemoryUsage().getMax();
    }
    
Returns the heap memory committed to the JVM.

Returns:
Heap memory currently committed to the JVM in bytes.
    public double heapCommitted() {
        return .getHeapMemoryUsage().getCommitted();
    }

    
Returns the percentage of the JVM's heap which is being used.

Returns:
the percentage of the JVM's heap which is being used
    public double heapUsage() {
        final MemoryUsage usage = .getHeapMemoryUsage();
        return usage.getUsed() / (doubleusage.getMax();
    }

    
Returns the percentage of the JVM's non-heap memory (e.g., direct buffers) which is being used.

Returns:
the percentage of the JVM's non-heap memory which is being used
    public double nonHeapUsage() {
        final MemoryUsage usage = .getNonHeapMemoryUsage();
        return usage.getUsed() / (doubleusage.getMax();
    }

    
Returns a map of memory pool names to the percentage of that pool which is being used.

Returns:
a map of memory pool names to the percentage of that pool which is being used
    public Map<StringDoublememoryPoolUsage() {
        final Map<StringDoublepools = new TreeMap<StringDouble>();
        for (MemoryPoolMXBean pool : ) {
            final double max = pool.getUsage().getMax() == -1 ?
                    pool.getUsage().getCommitted() :
                    pool.getUsage().getMax();
            pools.put(pool.getName(), pool.getUsage().getUsed() / max);
        }
        return Collections.unmodifiableMap(pools);
    }

    
Returns the percentage of available file descriptors which are currently in use.

Returns:
the percentage of available file descriptors which are currently in use, or NaN if the running JVM does not have access to this information
    public double fileDescriptorUsage() {
        try {
            final Method getOpenFileDescriptorCount = .getClass().getDeclaredMethod("getOpenFileDescriptorCount");
            getOpenFileDescriptorCount.setAccessible(true);
            final Long openFds = (LonggetOpenFileDescriptorCount.invoke();
            final Method getMaxFileDescriptorCount = .getClass().getDeclaredMethod("getMaxFileDescriptorCount");
            getMaxFileDescriptorCount.setAccessible(true);
            final Long maxFds = (LonggetMaxFileDescriptorCount.invoke();
            return openFds.doubleValue() / maxFds.doubleValue();
        } catch (NoSuchMethodException e) {
            return .;
        } catch (IllegalAccessException e) {
            return .;
        } catch (InvocationTargetException e) {
            return .;
        }
    }

    
Returns the version of the currently-running jvm.

Returns:
the version of the currently-running jvm, eg "1.6.0_24"
See also:
J2SE SDK/JRE Version String Naming Convention
    public String version() {
        return System.getProperty("java.runtime.version");
    }

    
Returns the name of the currently-running jvm.

Returns:
the name of the currently-running jvm, eg "Java HotSpot(TM) Client VM"
See also:
System.getProperties()
    public String name() {
        return System.getProperty("java.vm.name");
    }

    
Returns the number of seconds the JVM process has been running.

Returns:
the number of seconds the JVM process has been running
    public long uptime() {
        return ..toSeconds(.getUptime());
    }

    
Returns the number of live threads (includes daemonThreadCount().

Returns:
the number of live threads
    public int threadCount() {
        return .getThreadCount();
    }

    
Returns the number of live daemon threads.

Returns:
the number of live daemon threads
    public int daemonThreadCount() {
        return .getDaemonThreadCount();
    }

    
Returns a map of garbage collector names to garbage collector information.

Returns:
a map of garbage collector names to garbage collector information
        final Map<StringGarbageCollectorStatsstats = new HashMap<StringGarbageCollectorStats>();
        for (GarbageCollectorMXBean gc : ) {
            stats.put(gc.getName(),
                      new GarbageCollectorStats(gc.getCollectionCount(),
                                                gc.getCollectionTime()));
        }
        return Collections.unmodifiableMap(stats);
    }

    
Returns a set of strings describing deadlocked threads, if any are deadlocked.

Returns:
a set of any deadlocked threads
    public Set<StringdeadlockedThreads() {
        final long[] threadIds = .findDeadlockedThreads();
        if (threadIds != null) {
            final Set<Stringthreads = new HashSet<String>();
            for (ThreadInfo info : this..getThreadInfo(threadIds)) {
                final StringBuilder stackTrace = new StringBuilder();
                for (StackTraceElement element : info.getStackTrace()) {
                    stackTrace.append("\t at ").append(element.toString()).append('\n');
                }
                threads.add(
                        String.format(
                                "%s locked on %s (owned by %s):\n%s",
                                info.getThreadName(), info.getLockName(),
                                info.getLockOwnerName(),
                                stackTrace.toString()
                        )
                );
            }
            return Collections.unmodifiableSet(threads);
        }
        return Collections.emptySet();
    }

    
Returns a map of thread states to the percentage of all threads which are in that state.

Returns:
a map of thread states to percentages
    public Map<StateDoublethreadStatePercentages() {
        final Map<StateDoubleconditions = new HashMap<StateDouble>();
        for (State state : State.values()) {
            conditions.put(state, 0.0);
        }
        final long[] allThreadIds = .getAllThreadIds();
        final ThreadInfo[] allThreads = .getThreadInfo(allThreadIds);
        int liveCount = 0;
        for (ThreadInfo info : allThreads) {
            if (info != null) {
                final State state = info.getThreadState();
                conditions.put(stateconditions.get(state) + 1);
                liveCount++;
            }
        }
        for (State state : new ArrayList<State>(conditions.keySet())) {
            conditions.put(stateconditions.get(state) / liveCount);
        }
        return Collections.unmodifiableMap(conditions);
    }

    
Dumps all of the threads' current information to an output stream.

Parameters:
out an output stream
    public void threadDump(OutputStream out) {
        final ThreadInfo[] threads = this..dumpAllThreads(truetrue);
        final PrintWriter writer = new PrintWriter(outtrue);
        for (int ti = threads.length - 1; ti >= 0; ti--) {
            final ThreadInfo t = threads[ti];
            writer.printf("%s id=%d state=%s",
                          t.getThreadName(),
                          t.getThreadId(),
                          t.getThreadState());
            final LockInfo lock = t.getLockInfo();
            if (lock != null && t.getThreadState() != ..) {
                writer.printf("\n    - waiting on <0x%08x> (a %s)",
                              lock.getIdentityHashCode(),
                              lock.getClassName());
                writer.printf("\n    - locked <0x%08x> (a %s)",
                              lock.getIdentityHashCode(),
                              lock.getClassName());
            } else if (lock != null && t.getThreadState() == ..) {
                writer.printf("\n    - waiting to lock <0x%08x> (a %s)",
                              lock.getIdentityHashCode(),
                              lock.getClassName());
            }
            if (t.isSuspended()) {
                writer.print(" (suspended)");
            }
            if (t.isInNative()) {
                writer.print(" (running in native)");
            }
            writer.println();
            if (t.getLockOwnerName() != null) {
                writer.printf("     owned by %s id=%d\n"t.getLockOwnerName(), t.getLockOwnerId());
            }
            final StackTraceElement[] elements = t.getStackTrace();
            final MonitorInfo[] monitors = t.getLockedMonitors();
            for (int i = 0; i < elements.lengthi++) {
                final StackTraceElement element = elements[i];
                writer.printf("    at %s\n"element);
                for (int j = 1; j < monitors.lengthj++) {
                    final MonitorInfo monitor = monitors[j];
                    if (monitor.getLockedStackDepth() == i) {
                        writer.printf("      - locked %s\n"monitor);
                    }
                }
            }
            writer.println();
            final LockInfo[] locks = t.getLockedSynchronizers();
            if (locks.length > 0) {
                writer.printf("    Locked synchronizers: count = %d\n"locks.length);
                for (LockInfo l : locks) {
                    writer.printf("      - %s\n"l);
                }
                writer.println();
            }
        }
        writer.println();
        writer.flush();
    }
    
        try {
            final String[] attributes = { "Count""MemoryUsed""TotalCapacity" };
            final ObjectName direct = new ObjectName("java.nio:type=BufferPool,name=direct");
            final ObjectName mapped = new ObjectName("java.nio:type=BufferPool,name=mapped");
            final AttributeList directAttributes = .getAttributes(directattributes);
            final AttributeList mappedAttributes = .getAttributes(mappedattributes);
            final Map<StringBufferPoolStatsstats = new TreeMap<StringBufferPoolStats>();
            final BufferPoolStats directStats = new BufferPoolStats((Long) ((AttributedirectAttributes.get(0)).getValue(),
                                                                    (Long) ((AttributedirectAttributes.get(1)).getValue(),
                                                                    (Long) ((AttributedirectAttributes.get(2)).getValue());
            stats.put("direct"directStats);
            final BufferPoolStats mappedStats = new BufferPoolStats((Long) ((AttributemappedAttributes.get(0)).getValue(),
                                                                    (Long) ((AttributemappedAttributes.get(1)).getValue(),
                                                                    (Long) ((AttributemappedAttributes.get(2)).getValue());
            stats.put("mapped"mappedStats);
            return Collections.unmodifiableMap(stats);
        } catch (JMException e) {
            return Collections.emptyMap();
        }
    }
New to GrepCode? Check out our FAQ X