CSDN博客

img luco

JVM-independent solution to flushing memory

发表于2004/10/5 2:30:00  678人阅读

http://www.onjava.com/pub/a/onjava/2001/08/22/optimization.html

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:

public static void flushMemory()
{
  //Use a vector to hold the memory.
  Vector v = new Vector();
  int count = 0;
  //increment in megabyte chunks initially
  int size = 1048576;
  //Keep going until we would be requesting 
  //chunks of 1 byte
  while(size > 1)
  {
    try
    {
      for (; true ; count++)
      {
        //request and hold onto more memory
        v.addElement( new byte[size] );
      }
    }
    //If we encounter an OutOfMemoryError, keep 
    //trying to get more memory, but asking for 
    //chunks half as big.
    catch (OutOfMemoryError bounded){size = size/2;}
  }
  //Now release everything for GC
  v = null;
  //and ask for a new Vector as a new small object 
  //to make sure garbage collection kicks in before 
  //we exit the method.
  v = new Vector();
}

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.

 

阅读全文
0 0

相关文章推荐

img
取 消
img