Java Utililty Methods Memory

List of utility methods to do Memory

Description

The list of methods to do Memory are organized into topic(s).

Method

longalignMemory(long numBytes)
Most current VMs have memory alignment that places objects into heap space that is a multiple of 8 Bytes.
long remainder = numBytes % 8;
if (remainder != 0) {
    numBytes += (8 - remainder);
return numBytes;
booleancheckLowMemory()
check Low Memory
return checkLowMemory(0.2);
longcheckMemory()
check Memory
return (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory());
voidcheckMinMemory(long min)
Exits with code -1 if maximum memory is below 90% of minimally allowed threshold.
long maxMem = Runtime.getRuntime().maxMemory();
if (maxMem < .85 * min) {
    System.err.println("Heap limit is too low (" + (maxMem / (1024 * 1024))
            + "MB), please increase heap size at least up to " + (min / (1024 * 1024)) + "MB.");
    System.exit(-1);
voidcompactMemory()
Compacts memory as much as possible by allocating huge memory block and then forcing garbage collection.
try {
    final byte[][] unused = new byte[128][];
    for (int i = unused.length; i-- != 0;) {
        unused[i] = new byte[2000000000];
} catch (OutOfMemoryError ignore) {
System.gc();
...
longcorrectMemoryValue(int memory)
correct Memory Value
long mem = memory;
if (mem < 0) {
    mem -= Integer.MIN_VALUE;
    mem += Integer.MAX_VALUE;
return mem;
voiddisplayMemory(String label, long bytes)
display Memory
long memoryKBytes = bytes / 1024;
long memoryMBytes = memoryKBytes / 1024;
System.out.println(label + " = " + bytes + " bytes, " + memoryKBytes + "KB, " 
        + memoryMBytes + "MB"); 
voiddumpMemory()
dump Memory
System.out.println("\n" + "Max. memory: " + Runtime.getRuntime().maxMemory() / 1024 / 1024 + " MB" + "\n"
        + "Tot. memory: " + Runtime.getRuntime().totalMemory() / 1024 / 1024 + " MB" + "\n"
        + "Free memory: " + Runtime.getRuntime().freeMemory() / 1024 / 1024 + " MB");
voiddumpMemoryInfo(String msg)
Dumps out memory information
Runtime rt = Runtime.getRuntime();
long free = rt.freeMemory();
rt.gc();
long reclaimedMemory = (rt.freeMemory() - free) / (1024 * 1024);
long freeMemory = rt.freeMemory() / (1024 * 1024);
long totalMemory = rt.totalMemory() / (1024 * 1024);
long usedMemory = rt.totalMemory() - rt.freeMemory();
if (usedMemory > maxUsed) {
...
ObjectfillMemory()
Fills memory and returns an object that refers to all of what was allocated.
byte[][] arrays = new byte[100][];
int size = 1 << 30;
int idx = 0;
while (true) {
    try {
        while (true) {
            arrays[idx++] = new byte[size];
    } catch (OutOfMemoryError oome) {
        if (size == 0) {
            break;
        } else {
            size /= 2;
return arrays;