1

I have some questions about Jvm memory management:

1) if two methods or functions are running in background continuously, is it possible to find out that which one is taking more memory?

2) if this is possible then can we do this using Java Reflection ?

Coder
  • 1,129
  • 10
  • 24
  • before/after execution your function put a debug log and in that print the difference of jvm heap memory – shivam Nov 16 '18 at 06:30
  • Please refer this https://stackoverflow.com/questions/6487802/check-available-heapsize-programmatically – shivam Nov 16 '18 at 06:30

1 Answers1

0

I'm not sure what you mean by "taking more memory", but it is definitely possible to find which one allocates more memory. This can be done both from inside the application and from outside.

Inside the application

private static final com.sun.management.ThreadMXBean threadMXBean =
        (com.sun.management.ThreadMXBean) ManagementFactory.getThreadMXBean();

public void myAllocatingMethod() {
    long before = threadMXBean.getThreadAllocatedBytes(Thread.currentThread().getId());

    // ... some business logic that allocates memory ...
    byte[] array = new byte[500000];

    long after = threadMXBean.getThreadAllocatedBytes(Thread.currentThread().getId());
    System.out.println("Method allocated " + (after - before) + " bytes");
}

Note: this counts memory allocated in the context of current thread. If a method spawns new threads or executes some code in a thread pool, it's not obvious how to account the allocated memory to a particular method.

Outside the application

Use allocation profilers like Java Mission Control.

P.S. Java Reflection has nothing to do with memory measurements.

apangin
  • 92,924
  • 10
  • 193
  • 247