Image

Imagetalldean wrote in Imagejava_dev

sizeOf. In Java.

So, got pissed that Java doesn't seem to have anything to help one figure out how much memory individual user sessions are taking up. Having HttpSession support a size() method would be, well, too easy. Anyone have any comments on this? This was cobbled out of something on JGuru.com, and cleaned up a bit.
package util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;


/**
 * Return the size of a Java Object.
 * The object must implement java.io.Serializable
 */
public class SizeOf {

	/**
	 * Return the size of a Java Object, in bytes.
	 * Return -1 if this fails.
	 */
	public static int sizeOf(Object o) throws IOException {

		int counter = -1;

		ByteArrayOutputStream baos = null;
		ObjectOutputStream oos = null;
		try {
			baos = new ByteArrayOutputStream();
			oos = new ObjectOutputStream(baos);
			oos.writeObject(o);
			oos.flush();

			// Serialization adds 4 bytes to an object; remove that.
			counter += baos.toByteArray().length - 4;
		} finally {
			if (oos != null) { try { oos.close(); } catch (Exception e) { ; } }
			if (baos != null) { try { baos.close(); } catch (Exception e) { ; } }
		}

		return counter;
	}

	/**
	 * Return the size of a Java Object, in kbytes.
	 */
	public static int kSizeOf(Object o) throws IOException {
		int temp = sizeOf(o);
		if (temp == -1) {
			return -1;
		} else {
			return temp / 1024;
		}
	}
}