Java performance improvement through Java Parameters)
Author: aiqun technology Xiao songyu
We all know that Java will eat a lot of memory during execution, and when the memory is not enough
When it is used, the JVM will ask the system for more memory to use. But in fact, for JA
For VA, we will find that there are many different data types, including two important
Is heap and stack. What is the difference between the two? We will mention it later,
Before that, let's look at a program:
Public class testheap
{
Public static void main (string argv [])
{
Stringbuffer sb = new stringbuffer ();
Long starttime;
Long endtime;
Starttime = system. currenttimemillis ();
For (INT I = 0; I & lt; = 100000; I ++)
{
SB. append (I). append (& quot; Hello & quot;). append (I );
If (I % (100000/2) = 0)
{
System. Out. println (runtime. getruntime (). totalme
Mory ());
}
}
Endtime = system. currenttimemillis ();
System. Out. println (& quot; Time: & quot; + (endtime-starttim
E ));
}
}
The execution result is as follows:
C:/Java/tmp & gt; Java testheap
2031616
5578752
10498048
Time: 651
Here, we can see that totalmemory continues to rise. Of course, this is a normal phenomenon,
In fact, we can control the memory size captured by JVM at the beginning. The advantage is that
JVM captured a large number of heap at the beginning. How can this problem be solved? Let's first use Java-X to see
Let's see what additional parameters he has. That's right. I can see the parameters I'm interested in.
-XMS & lt; size & gt; set initial Java heap size
-Xmx & lt; size & gt; set maximum Java heap size
-XSS & lt; size & gt; Set Java thread stack size
Next, I want the JVM to capture a large amount of memory from the beginning, so I choose-XMS
Below is my execution result:
C:/Java/tmp & gt; Java-xms50000000 testheap
49741824
49741824
49741824
Time: 480
At this time, we can see that the total memory remains unchanged, the reason is very simple, because testhea
The amount of memory used by P does not exceed the amount we caught at the beginning. But there is an interesting
The phenomenon is that the cycle time is shorter. In other words, it means that the program runs more quickly.
Efficiency. This method of exchanging memory space for execution time may not be the best school.
But it is a way to improve efficiency without modifying the code. Of course
We can also limit the maximum memory usage. The parameter is-xmx. Generally
It is not recommended that you set-xmx for the simple reason, because once you set-xmx, then the JVM
After the captured memory reaches this value, it will not capture the memory, that is, you
The program cannot be executed. Let's look at the following results.
C:/Java/tmp & gt; Java-xmx5000000 testheap
2031616
5578752
Exception in thread & quot; Main & quot; Java. Lang. outofmemoryerror
C:/Java/tmp & gt;