JVM-Independent Solution to Flushing Memory

xiaoxiao2021-03-06  61

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 10 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 would not 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.

转载请注明原文地址:https://www.9cbs.com/read-110495.html

New Post(0)