
package org.jboss.cache;

import java.util.LinkedHashMap;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.LinkedList;
import java.util.ArrayList;

/**
 * Measure the size of an object by allocating a bunch of them and
 * seeing how much heap memory was consumed.
 * 
 * Created on Apr 8, 2003 3:59:14 PM
 * @author mroth
 */
public class SizeOf {

	public static void main(String[] argv) throws Exception {

		System.out.println("SizeOf: (bytes)");
    for (int i = 0; i < argv.length; i++)
      reportSize(Class.forName(argv[i]));

	}

	private static void reportSize(Class s) throws Exception {
		System.out.println(s + ": " + estimateSize(s));
	}

	public static long estimateSize(Class s) throws Exception {
		final int n = 100000;
		Object[] array = new Object[n];
		giveGarbageCollectionAChance();
		long before = getUsedMemory();
		for (int i = 0; i < n; i++) {
      Object dummy = s.newInstance();
      array[i] = dummy;
		}
		giveGarbageCollectionAChance();
		long after = getUsedMemory();
    long diff = after - before;

		return Math.round((double) (diff) / (double) n);
	}

	private static void giveGarbageCollectionAChance() {
		try {
			Thread.sleep(1000);
      System.gc();
			Thread.sleep(1000);
      System.gc();
		} catch (InterruptedException e) {
			// ignore - should not happen
		}
	}

	private static long getUsedMemory() {
		Runtime r = Runtime.getRuntime();
		return r.totalMemory() - r.freeMemory();
	}

}
