Skip to content

Instantly share code, notes, and snippets.

@electrum
Created August 13, 2015 16:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save electrum/5a97bb1e4db4a9cf68de to your computer and use it in GitHub Desktop.
Save electrum/5a97bb1e4db4a9cf68de to your computer and use it in GitHub Desktop.
import com.sun.management.ThreadMXBean;
import java.lang.management.ManagementFactory;
import java.util.Arrays;
public final class ThreadMemory
{
public static void main(String[] args)
{
ThreadMXBean threadMXBean = (ThreadMXBean) ManagementFactory.getThreadMXBean();
System.out.printf("supported=%s enabled=%s%n",
threadMXBean.isThreadAllocatedMemorySupported(),
threadMXBean.isThreadAllocatedMemoryEnabled());
for (int i = 1; i <= 5; i++) {
int size = i;
new Thread(() -> {
long threadId = Thread.currentThread().getId();
long start = threadMXBean.getThreadAllocatedBytes(threadId);
System.out.printf("thread %s start: allocated=%s%n", threadId, start);
int actual = 0;
for (int j = 0; j < 2000; j++) {
byte[] bytes = new byte[size * 500];
Arrays.fill(bytes, (byte) 42);
actual += bytes.length;
}
long end = threadMXBean.getThreadAllocatedBytes(threadId);
System.out.printf("thread %s end: allocated=%s delta=%s actual=%s %n", threadId, end, end - start, actual);
}).start();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment