Java Memory Free getMemoryFree()

Here you can find the source of getMemoryFree()

Description

Get the free memory in KB.

License

Mozilla Public License

Return

the free memory

Declaration

public static int getMemoryFree() 

Method Source Code

//package com.java2s;
/*// www  .  j a  v a 2s .  co  m
 * Copyright 2004-2014 H2 Group. Multiple-Licensed under the MPL 2.0,
 * and the EPL 1.0 (http://h2database.com/html/license.html).
 * Initial Developer: H2 Group
 */

public class Main {
    private static final int GC_DELAY = 50;
    private static final int MAX_GC = 8;
    private static long lastGC;

    /**
     * Get the free memory in KB.
     * This method possibly calls System.gc().
     *
     * @return the free memory
     */
    public static int getMemoryFree() {
        collectGarbage();
        Runtime rt = Runtime.getRuntime();
        long mem = rt.freeMemory();
        return (int) (mem >> 10);
    }

    private static synchronized void collectGarbage() {
        Runtime runtime = Runtime.getRuntime();
        long total = runtime.totalMemory();
        long time = System.currentTimeMillis();
        if (lastGC + GC_DELAY < time) {
            for (int i = 0; i < MAX_GC; i++) {
                runtime.gc();
                long now = runtime.totalMemory();
                if (now == total) {
                    lastGC = System.currentTimeMillis();
                    break;
                }
                total = now;
            }
        }
    }
}

Related

  1. getFreeMemoryKb()
  2. getFreeMemoryMB()
  3. getJavaFreeMemory()
  4. getJvmFreeMemory()
  5. getMemoryFree()
  6. getSystemFreeMemory()
  7. getTilesBasedOnFreeMemory(int rows, int cols)
  8. hasFreeMemory(float margin)
  9. isFreeMemoryAvailable()