Created
December 16, 2011 14:53
-
-
Save buzztaiki/1486341 to your computer and use it in GitHub Desktop.
Monitor GC
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.lang.management.GarbageCollectorMXBean; | |
| import java.lang.management.ManagementFactory; | |
| import java.util.concurrent.Executors; | |
| import java.util.concurrent.ScheduledExecutorService; | |
| import java.util.concurrent.TimeUnit; | |
| public class GCMonitor implements Runnable { | |
| private final GarbageCollectorMXBean mbean; | |
| private long lastGCCount; | |
| private long lastGCTime; | |
| public GCMonitor(GarbageCollectorMXBean mbean) { | |
| this.mbean = mbean; | |
| this.lastGCCount = mbean.getCollectionCount(); | |
| this.lastGCTime = mbean.getCollectionTime(); | |
| } | |
| public void run() { | |
| long newGCCount = mbean.getCollectionCount(); | |
| long newGCTime = mbean.getCollectionTime(); | |
| if (newGCCount > lastGCCount) { | |
| System.out.format( | |
| "Full GC: count=%d, time=%dms, totalCount=%d, totalTime=%dms%n", | |
| newGCCount - lastGCCount, newGCTime - lastGCTime, newGCCount, newGCTime); | |
| lastGCCount = newGCCount; | |
| lastGCTime = newGCTime; | |
| } | |
| } | |
| private static GarbageCollectorMXBean markSweepGCBean(Iterable<GarbageCollectorMXBean> gcbeans) { | |
| for (GarbageCollectorMXBean gcbean : gcbeans) { | |
| if (gcbean.getName().indexOf("MarkSweep") >= 0) { | |
| return gcbean; | |
| } | |
| } | |
| return null; | |
| } | |
| public static void main(String[] args) throws Exception { | |
| long gcWait = args.length == 0 ? 100: Long.parseLong(args[0]); | |
| GarbageCollectorMXBean mbean = markSweepGCBean(ManagementFactory.getGarbageCollectorMXBeans()); | |
| if (mbean == null) { | |
| return; | |
| } | |
| ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); | |
| scheduler.scheduleWithFixedDelay(new GCMonitor(mbean), 1, 1, TimeUnit.SECONDS); | |
| try { | |
| for (;;) { | |
| Thread.sleep(gcWait); | |
| System.gc(); | |
| } | |
| } finally { | |
| scheduler.shutdown(); | |
| scheduler.awaitTermination(5, TimeUnit.SECONDS); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment