package Tools;

import java.text.NumberFormat;

/**
 * A Tool for examining the current amount of memory in use by the JVM.
 * Great for finding memory ``leaks'' such as leaving things in hash
 * tables that you didn't intend. I first used it to get a handle on
 * how much memory I was using when indexing the cells in my {@link
 * relational} databases.
 */
public class Memory {
	long startMem;
	long endMem;
	boolean lapped;
	Runtime rt;

	static NumberFormat nf;
	static {
		nf = NumberFormat.getInstance();
		nf.setMaximumFractionDigits(2);
		nf.setMinimumFractionDigits(2);
	}

	public Memory() {
		rt = Runtime.getRuntime();
		System.gc();
		startMem = rt.totalMemory() - rt.freeMemory();
		endMem = 0L;
		lapped = false;
	}

	public void lap() {
		System.gc();
		endMem = rt.totalMemory() - rt.freeMemory();
		lapped = true;
	}

	public long getMemory() {
		if (!lapped) lap();
		return endMem - startMem;
	}

	public double getMB() {
		return ((double)getMemory())/1048576.0;
	}

	public String toString() {
		return nf.format(getMB())+"MB";
	}
}
