List of utility methods to do Memory
long | alignMemory(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; |
boolean | checkLowMemory() check Low Memory return checkLowMemory(0.2);
|
long | checkMemory() check Memory return (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory());
|
void | checkMinMemory(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); |
void | compactMemory() 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(); ... |
long | correctMemoryValue(int memory) correct Memory Value long mem = memory; if (mem < 0) { mem -= Integer.MIN_VALUE; mem += Integer.MAX_VALUE; return mem; |
void | displayMemory(String label, long bytes) display Memory long memoryKBytes = bytes / 1024; long memoryMBytes = memoryKBytes / 1024; System.out.println(label + " = " + bytes + " bytes, " + memoryKBytes + "KB, " + memoryMBytes + "MB"); |
void | dumpMemory() 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"); |
void | dumpMemoryInfo(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) { ... |
Object | fillMemory() 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; |