Here you can find the source of getMemoryUsage()
private static long getMemoryUsage()
//package com.java2s; /*//from w w w . j a v a 2s . co m * Copyright 2016 Generic Problem Solver Project * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ public class Main { /** * The runtime object currently used to communicate with the environment */ private static final Runtime runtime = Runtime.getRuntime(); /** * Returns the amount of memory currently used by the JVM. * * @return The amount of memory used in bytes. Calculated by totalMemory-freeMemory */ private static long getMemoryUsage() { hardClean(); return runtime.totalMemory() - runtime.freeMemory(); } /** * Will clear as much memory as possible, resulting in a more accurate comparision */ private static void hardClean() { // Running it once is actually not enough // Running it multiple times results in a way more accurate memory reading for (int i = 0; i < 5; ++i) { runtime.runFinalization(); Thread.yield(); runtime.gc(); } } }