Use the following function to get exact information. It is generated by taking the base of the ATM_CashWithdrawl concept.
getFullMemoryUnit(): Total: [123 MB], Max: [1 GB, 773 MB, 512 KB], Free: [120 MB, 409 KB, 304 Bytes]
public static String getFullMemoryUnit(long unit) { long BYTE = 1024, KB = BYTE, MB = KB * KB, GB = MB * KB, TB = GB * KB; long KILO_BYTE, MEGA_BYTE = 0, GIGA_BYTE = 0, TERA_BYTE = 0; unit = Math.abs(unit); StringBuffer buffer = new StringBuffer(); if ( unit / TB > 0 ) { TERA_BYTE = (int) (unit / TB); buffer.append(TERA_BYTE+" TB"); unit -= TERA_BYTE * TB; } if ( unit / GB > 0 ) { GIGA_BYTE = (int) (unit / GB); if (TERA_BYTE != 0) buffer.append(", "); buffer.append(GIGA_BYTE+" GB"); unit %= GB; } if ( unit / MB > 0 ) { MEGA_BYTE = (int) (unit / MB); if (GIGA_BYTE != 0) buffer.append(", "); buffer.append(MEGA_BYTE+" MB"); unit %= MB; } if ( unit / KB > 0 ) { KILO_BYTE = (int) (unit / KB); if (MEGA_BYTE != 0) buffer.append(", "); buffer.append(KILO_BYTE+" KB"); unit %= KB; } if ( unit > 0 ) buffer.append(", "+unit+" Bytes"); return buffer.toString(); }
I have just modified the code of facebookarchive-StringUtils to get the below format. The same format you will get when you use apache.hadoop-StringUtils
getMemoryUnit(): Total: [123.0 MB], Max: [1.8 GB], Free: [120.4 MB]
public static String getMemoryUnit(long bytes) { DecimalFormat oneDecimal = new DecimalFormat("0.0"); float BYTE = 1024.0f, KB = BYTE, MB = KB * KB, GB = MB * KB, TB = GB * KB; long absNumber = Math.abs(bytes); double result = bytes; String suffix = " Bytes"; if (absNumber < MB) { result = bytes / KB; suffix = " KB"; } else if (absNumber < GB) { result = bytes / MB; suffix = " MB"; } else if (absNumber < TB) { result = bytes / GB; suffix = " GB"; } return oneDecimal.format(result) + suffix; }
Example usage of the above methods:
public static void main(String[] args) { Runtime runtime = Runtime.getRuntime(); int availableProcessors = runtime.availableProcessors(); long heapSize = Runtime.getRuntime().totalMemory(); long heapMaxSize = Runtime.getRuntime().maxMemory(); long heapFreeSize = Runtime.getRuntime().freeMemory(); System.out.format("Total: [%s], Max: [%s], Free: [%s]\n", heapSize, heapMaxSize, heapFreeSize); System.out.format("getMemoryUnit(): Total: [%s], Max: [%s], Free: [%s]\n", getMemoryUnit(heapSize), getMemoryUnit(heapMaxSize), getMemoryUnit(heapFreeSize)); System.out.format("getFullMemoryUnit(): Total: [%s], Max: [%s], Free: [%s]\n", getFullMemoryUnit(heapSize), getFullMemoryUnit(heapMaxSize), getFullMemoryUnit(heapFreeSize)); }
Bytes to get the above format
Total: [128974848], Max: [1884815360], Free: [126248240]
In order to display time in a human-readable format, use the function millisToShortDHMS(long duration).