Get Java program run-time Memory information

Source: Internet
Author: User
Tags visualvm

Because recently want to self-test the efficiency of string and stringbuffer, need to get the program run memory accounted for in the information, and then surf the internet, according to the information found to write a program, find the result is a problem, Only to find that the information found is wrong. So I'll share it with you here. The correct way to get memory consumption

The wrong way
//程序开始时:(先调用一下垃圾回收,但是不一定立即执行)Runtime.getRuntime().gc();long initm=Runtime.getRuntime().freeMemory();//程序结束时:Runtime.getRuntime().gc();long endm=Runtime.getRuntime().freeMemory();//计算空闲差:System.out.println(initm-endm);
About gcMethod

First, the call was really correct at the very beginning Runtime.getRuntime().gc() , but the comment says

Call garbage collection first, but not necessarily immediately

There is a problem with this phrase, as described in the Java API documentation for GC methods:

The invocation gc method implies that the Java virtual machine has made some effort to reclaim unused objects so that the memory currently occupied by these objects can be reused quickly. When control is returned from a method call, the virtual machine has tried its best to reclaim space from all discarded objects .

That is, the gc Java Virtual machine must be garbage collected when it is called. So why is it not necessarily done on the Internet or even in many textbooks gc ? Personal speculation may be that after running the gc method, memory consumption may not be significantly reduced, Because at this time there may not be much garbage that can be recycled. And after a while the JVM recycles the memory again, and this time the memory consumption is significantly reduced. So many places will say that the gc method is not necessarily immediately executed.

The second time you get "memory", you cannot invoke the gc method because doing so will reclaim some intermediate temporary variables, resulting in the acquisition of "memory" not necessarily the amount of "memory" actually used during the run.

About freeMemoryMethod

Then use the freeMemory method to get two times the free memory, and then subtract should be the memory consumed when the execution?
If the total amount of memory is not changed, then this method can do:

Total Memory 1 = free memory at start + Start with memory
Total Memory 2 = idle memory at end + memory at end
Total Memory 1 = Total Memory 2

The following formula can be introduced:

Free memory at start-idle memory at end
= Total Memory 1-memory used at start-(Total Memory 2-memory used at end)
= Use memory at end-start with memory

But the description of the method in the Java API documentation totalMemory is:

Returns the total amount of memory in the Java virtual machine. The value returned by this method may change over time , depending on the host environment.

This means that the total amount of memory is likely to change, that is, cannot be used, that is, the 开始时空闲内存-结束时空闲内存 amount of 结束时使用内存 - 开始时使用内存 memory used.
So, what if we get run-time memory usage? Please continue looking down.

Get memory usage in a Java program

Let's first talk about getting runtime memory in a Java program, on the code:

Runtime run = Runtime.getruntime (); System.in.read ();//Suspend program execution//System.out.println ("memory> total:" + run.totalmemory () + "free:" + run.freememory () + "used:" + (Run.totalmem Ory ()-run.freememory ()));RUN.GC (); System.out.println ("Time:"+ (NewDate ()));//Get start memory consumptionLongStartmem = Run.totalmemory ()-run.freememory (); System.out.println ("memory> total:"+ run.totalmemory () +"Free:"+ run.freememory () +"used:"+ Startmem); String str =""; for(intI=0; i<50000; ++i) {str + = i;} System.out.println ("Time:"+ (NewDate ()));LongEndmem = Run.totalmemory ()-run.freememory (); System.out.println ("memory> total:"+ run.totalmemory () +"Free:"+ run.freememory () +"used:"+ Endmem); System.out.println ("Memory difference:"+ (ENDMEM-STARTMEM));/*run.gc (); System.out.println ("memory> total:" + run.totalmemory () + "free:" + run.freememory () + "used:" + (Run.totalmemory ()-R Un.freememory ())); * *

There is no overly complex logic in the code, and System.in.read the reason for calling the method to pause the program and printing the current time is explained later.
The one output of this program on my computer is:

Because the total amount of memory is increased by 5 times times (the total memory is the amount of memory that is seen in the Task Manager), and the free memory is increased, the 开始时空闲内存 - 结束时空闲内存 negative ...
This does not exclude the result of garbage collection, you can take a few more times to see the result: free memory is indeed growing. Of course, you can also cancel the lines of code comments to see the memory changes after the garbage collection has been performed.
Advantages of obtaining program memory consumption in code:

    • Without any other tools, you can roughly measure the memory that our program consumes.

Disadvantage is

    • It is possible that the JVM has just reclaimed garbage, and our program gets the amount of memory used, which results in a serious low result. But the probability is still very low.
    • We need to change our program. You will need to remove the code after the test is complete, and you may be inadvertently introducing a bug. This is the biggest problem!
Using tools

The Performance analysis tool makes it easy to get information such as program memory, CPU usage, and so on. There is no need to modify the program. Java's performance analysis tool is still a lot of, we use JVISUALVM. Its greatest advantage is that the JDK comes with its own, After installing the JDK, there will be JVISUALVM in the system. We can find in the %JAVA_HOME%/bin directory jvisualvm.exe , this program is very simple to use, we do not say the use of methods, the only thing to note is that VISUALVM "open" a program takes a while, if the "open" program when the program is finished, then we do not have any information, so we need to start the program to suspend the program. That's why we called the method at the very beginning. System.in.read
Open VISUALVM, and then run our program, and in VISUALVM, double-click to open our program for analysis. You can view information such as memory usage in the Monitoring tab. The following figure corresponds to the result of the above operation:


We can take a graph and our program output results in the corresponding time point of memory for the information used to compare. To get a more realistic memory footprint.
VISUALVM should be 1 seconds to get a memory usage, instead of taking this 1 second average, as the memory footprint of this 1 second, otherwise, the above image and the following pictures are not explained:


Finally, if your VISUALVM has a visual GC plugin installed, you can also get some information about garbage collection, such as the number of garbage collections and the approximate frequency:

From the picture can be seen, a total of 149 garbage collected, in the back a period of time, that is our cycle, garbage collection frequency is very high.

OK, let's talk about memory analysis. If there is something wrong, please advise me.

Written in 2015/05/15

Get Java program run-time Memory information

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.