Getting memory by thread

This is not perfect, as the heap is shared. However, the documentation indicates that a ThreadMXBean can calculate how much is in use by each.

The idea behind this would be to either instrument your code, or use byte code injection to insert calls to log what is in use after a given method returns. This would be a possible alternative to heap dumps run through Eclipse Memory Analyzer.

Drawbacks to this are some memory could show as allocated when it is actually eligible for garbage collection but has not yet been collected. That is the case below, as each StringBuffer is out of scope after each loop, yet the allocated memory number continues to climb. The thought is that over time these should average out to make the results more trustworthy.

bash-4.1$ cat threadMem.java
import java.lang.management.*;
import java.util.*;

public class threadMem implements Runnable {
  int j;
  public static void main (String args[]) throws Exception {
    Random r = new Random();
    for (int i = 1; i <= 1; i++) {
      threadMem tm = new threadMem(Math.abs(r.nextInt(Short.MAX_VALUE)));
    }
  }

  threadMem(int j) {
    Thread t = new Thread(this);
    this.j = j;
    t.start();
  }

  public void run() {
    for (int k = 1; k <= 10; k++) {
      StringBuffer sb = new StringBuffer();
      for (int i = 1; i <= this.j; i++)
        sb.append("*");
      long th = Thread.currentThread().getId();
      long bytes = ((com.sun.management.ThreadMXBean)ManagementFactory.getThreadMXBean()).getThreadAllocatedBytes(th);
      System.out.println("Thread " + th + ",size of string buffer " + this.j + ",total thread ram allocated " + bytes);
    }
  }
}
bash-4.1$ javac threadMem.java
bash-4.1$ java threadMem
Thread 8,size of string buffer 19919,total thread ram allocated 153648
Thread 8,size of string buffer 19919,total thread ram allocated 302672
Thread 8,size of string buffer 19919,total thread ram allocated 450960
Thread 8,size of string buffer 19919,total thread ram allocated 599248
Thread 8,size of string buffer 19919,total thread ram allocated 747536
Thread 8,size of string buffer 19919,total thread ram allocated 895824
Thread 8,size of string buffer 19919,total thread ram allocated 1044112
Thread 8,size of string buffer 19919,total thread ram allocated 1192704
Thread 8,size of string buffer 19919,total thread ram allocated 1341296
Thread 8,size of string buffer 19919,total thread ram allocated 1489888
bash-4.1$

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.