Created
October 16, 2013 14:23
-
-
Save svzdvd/7008537 to your computer and use it in GitHub Desktop.
This file contains 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.LockInfo; | |
import java.lang.management.ManagementFactory; | |
import java.lang.management.ThreadInfo; | |
import java.lang.management.ThreadMXBean; | |
import java.util.HashMap; | |
import java.util.Map; | |
/** | |
* http://stackoverflow.com/a/2362939 | |
*/ | |
public class JavaLockProfiler { | |
public static void main(String[] args) throws Exception { | |
Thread thr = new Thread() { | |
public void run() { | |
runProfile(); | |
} | |
}; | |
thr.setPriority(Thread.MAX_PRIORITY - 1); | |
thr.start(); | |
// TODO add code to profile here... | |
} | |
private static void runProfile() { | |
try { | |
final int noSeconds = 100; | |
final int sleepMillis = 50; | |
final int noSamples = noSeconds * 1000 / sleepMillis; | |
ThreadMXBean thb = ManagementFactory.getThreadMXBean(); | |
Map<String, Integer> blockCounts = new HashMap<String, Integer>(50); | |
for (int i = 0; i < noSamples; i++) { | |
long[] ids = thb.getAllThreadIds(); | |
ThreadInfo[] infs = thb.getThreadInfo(ids, 0); | |
for (ThreadInfo ti : infs) { | |
LockInfo lockInf = ti.getLockInfo(); | |
if (lockInf != null) { | |
String key = lockInf.toString(); | |
Integer cnt = blockCounts.get(key); | |
blockCounts.put(key, cnt == null ? 1 : cnt + 1); | |
} | |
} | |
Thread.sleep(sleepMillis); | |
} | |
System.out.println("Locks:"); | |
for (String lockName : blockCounts.keySet()) { | |
System.out.println(lockName + " : " + blockCounts.get(lockName)); | |
} | |
} catch (InterruptedException iex) { | |
Thread.currentThread().interrupt(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment