在IBM的虚拟机官方指导文档中明确指出,禁止将虚拟机的最大值和最小值设置为相等,否则会导致以下2个后果
<1>极大的增加垃圾回收时间,影响系统性能
<2>造成系统中存在内存碎片。
然而,BEA推荐将最小堆大小和最大堆大小设置为同一值,因为这样可以避免浪费用于时常调整堆大小所需的 VM 资源。
同样是堆大小,却有两种不同的说法,有必要来分析一下。
先看IBM的文章摘录:
IBM的虚拟机官方指导文档
Initial and maximum heap sizes
When you have established the maximum heap size that you need, you might want to set the minimum heap size to the same value; for example, -Xms 512M -Xmx 512M. Using the same values is not usually a good idea, because it delays the start of garbage collection until the heap is full. The first time that the Garbage Collector runs, therefore, becomes a very expensive operation. Also, the heap is most likely to be very fragmented when a need to do a heap compaction occurs. Again, this is a very expensive operation. The recommendation is to start your application with the minimum heap size that it needs. When it starts up, the Garbage Collector will run often and, because the heap is small, efficiently.
The Garbage Collector takes these steps:
If the Garbage Collector finds enough garbage, it exits.
If it cannot find enough garbage, it goes to the next step.
The Garbage Collector runs compaction.
If it cannot find enough garbage, it goes to the next step.
The Garbage collector expands the heap.
Therefore, an application normally runs until the heap is full. Then, successive garbage collection cycles recover garbage. When the heap is full of reachable objects, the Garbage Collector compacts the heap. If and when the heap is full of reachable objects and cannot be compacted, the Garbage Collector expands the heap size.
From the above description, you can see that the Garbage Collector compacts the heap as the needs of the application rise, so that as the heap expands, it expands with a set of compacted objects in the bottom of the original heap. This is an efficient way to manage the heap, because compaction runs on the smallest-possible heap size at the time that compaction is found to be necessary.
Compaction is performed with the minimum heap sizes as the heap grows. Some evidence exists that an application’s initial set of objects tends to be the key or root set, so that compacting them early frees the remainder of the heap for more short-lived objects.
Eventually, the JVM has the heap at maximum size with all long-lived objects compacted at the bottom of the heap. The compaction occurred when compaction was in its least expensive phase. The overheads of expanding the heap are almost trivial compared to the cost of collecting and compacting a very large fragmented heap.