# JVM-independent solution to flushing memory

http://www.onjava.com/pub/a/onjava/2001/08/22/optimization.html<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

Ideally, the JVM would provide a method that would flush memory for me. System.gc() looks like it should be such a call. Unfortunately, System.gc() is only a hint to the JVM that "now would be a good time to run the garbage collector." The JVM can ignore the hint, or can run a partial garbage collection, or a full mark-and-sweep of all spaces, or whatever. Instead of relying on the garbage collector, I adapt the method from the previous section to flush memory. I do this by allocating as much memory as possible, as with the earlier testMemory() method, and then I release all held memory and request a little more. The last request is to trigger the garbage collector to immediately reclaim all the memory I was holding onto. The method is straightforward:

This is a JVM-independent solution to flushing memory. You could even conceivably use this in an application if you knew that you had several seconds of time at some point when the application could be doing nothing else, but I wouldn't really recommend it. Although flushMemory() should work on any JVM, it is a stressful procedure and may break some JVMs. In particular I know that the Windows JVM from the Sun 1.2.0 release crashed the main thread when I ran flushMemory(), and put the garbage collector thread into a loop if I additionally ran with the -verbosegc option.

Operating system paging occurs when a program is too big to fit into available real memory (RAM), but can fit in virtual memory. Paging moves pages of the program back and forth between the RAM and the paging file on disk, allowing the operating system to seem like it has a larger memory than the available RAM, but at the expense of program performance.

• 本文已收录于以下专栏：

举报原因： 您举报文章：JVM-independent solution to flushing memory 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)