Get heap memory used by method in java class

I am writing Java code and I want to run some performance tests. I want to get the heap memory used by only one of the methods in my class.

 public AccessControl {

     public boolean Allowed () {
        code
        }
     public  void print () {
    code }
}

I want to get the heap memory used in java every time the Allowed method is called at runtime. I read that I can do this with HPROf, but I noticed that HPROf does not provide memory computation for methods, but only for classes, is there code that I can write inside the method to get the available memory and then the used memory? thank

+3
source share
5 answers

There is no such thing as “heap memory used by a method”. Ways do not take up heap memory, objects do.

, (, , , ), , ( ).

? , GC , , .

+1

InMemProfiler . .

# tracetarget-org.yourcode.YourClass, " ", YourClass.

. . , git fork InMemProfiler .

+1

, , . HPROF , , . JProfiler. , , , . .

0

oracle jvm, !

ThreadMXBean threadmx = ManagementFactory.getThreadMXBean();
long startbyte = ((com.sun.management.ThreadMXBean)threadmx)
    .getThreadAllocatedBytes(Thread.currentThread().getId());
//call method
int usedbyte = ((com.sun.management.ThreadMXBean)threadmx)
    .getThreadAllocatedBytes(Thread.currentThread().getId())-startbyte;
0

One way is to use a memory profiler such as jprofiler , but if you just want to see the memory used by the application set, the code below is used

Runtime runtime = Runtime.getRuntime();
long memoryUsedBefore = runtime.totalMemory() - runtime.freeMemory();
System.out.println("Memory used before: " + memoryUsedBefore );
    // set of memory consumption statements here
long memoryUsedAfter = runtime.totalMemory() - runtime.freeMemory();
System.out.println("Total Memory increased:" + (memoryUsedAfter - memoryUsedBefore ));
0
source

Source: https://habr.com/ru/post/1759135/


All Articles