Solved

Java Object Size in Memory

Posted on 2011-03-02
7
369 Views
Last Modified: 2012-05-11
I'm trying to determine how much heap memory is allocated for a java object (Object type could be List, String, Array, Map etc) in Web environment. I could not use Instrumentation package in web environment since I can not run javaAgent over there. Is there any way find object size in bytes in multi threading environment?
0
Comment
Question by:MatrixStar
7 Comments
 
LVL 47

Expert Comment

by:for_yan
ID: 35021145
0
 

Author Comment

by:MatrixStar
ID: 35021805
Yes, I had looked at Instrumentation way of doing and not the other one. I will try using reflection. But, there is no other API or classes, is it?
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35021865


I don't know about API, but there aslo some other things there - which are neither
Instrumentation nor Reflection, like this code based on creating and deleteing
object and measuraing garbage collection paparmeters - don't know how practical,
at least sounds interesting


http://stackoverflow.com/posts/757400/edit


A good generic solution is to use heap size delta.  This involves minimal effort and is re-usable between any type of object / object graph.  By instantiating and destroying your objects many times and garbage collecting in between, and then taking the average, you avoid compiler and JVM optimizations that alter results and get a fairly accurate result.  If you need an EXACT answer down to the byte then this may not be the solution for you, but for all practical applications that I know of (profiling, memory requirement calcualtions) it works extremely well.  The code below will do just that.
 

		public class Sizeof {
		  public static void main(String[] args)
			  throws Exception {
			// "warm up" all classes/methods that we are going to use:
			runGC();
			usedMemory();
		
			// array to keep strong references to allocated objects:
			final int count = 10000; // 10000 or so is enough for small ojects
			Object[] objects = new Object[count];
		
			long heap1 = 0;
		
			// allocate count+1 objects, discard the first one:
			for (int i = -1; i < count; ++i) {
			  Object object;
		
		//// INSTANTIATE YOUR DATA HERE AND ASSIGN IT TO 'object':
				
		
			  object=YOUR OBJECT;
		////end your code here
			  if (i >= 0) {
				objects[i] = object;
			  }
			  else {
				object = null; // discard the "warmup" object
				runGC();
				heap1 = usedMemory(); // take a "before" heap snapshot
			  }
			}
		
			runGC();
			long heap2 = usedMemory(); // take an "after" heap snapshot:
		
			final int size = Math.round(((float)(heap2 - heap1)) / count);
			System.out.println("'before' heap: " + heap1 +
							   ", 'after' heap: " + heap2);
			System.out.println("heap delta: " + (heap2 - heap1) +
							   ", {" + objects[0].getClass() + "} size = " + size + " bytes");
		  }
		
		  // a helper method for creating Strings of desired length
		  // and avoiding getting tricked by String interning:
		  public static String createString(final int length) {
			final char[] result = new char[length];
			for (int i = 0; i < length; ++i) {
			  result[i] = (char)i;
			}
		
			return new String(result);
		  }
		
		  // this is our way of requesting garbage collection to be run:
		  // [how aggressive it is depends on the JVM to a large degree, but
		  // it is almost always better than a single Runtime.gc() call]
		  private static void runGC()
			  throws Exception {
			// for whatever reason it helps to call Runtime.gc()
			// using several method calls:
			for (int r = 0; r < 4; ++r) {
			  _runGC();
			}
		  }
		
		  private static void _runGC()
			  throws Exception {
			long usedMem1 = usedMemory(), usedMem2 = Long.MAX_VALUE;
		
			for (int i = 0; (usedMem1 < usedMem2) && (i < 1000); ++i) {
			  s_runtime.runFinalization();
			  s_runtime.gc();
			  Thread.currentThread().yield();
		
			  usedMem2 = usedMem1;
			  usedMem1 = usedMemory();
			}
		  }
		
		  private static long usedMemory() {
			return s_runtime.totalMemory() - s_runtime.freeMemory();
		  }
		
		  private static final Runtime s_runtime = Runtime.getRuntime();
		
		} // end of class

Open in new window

0
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 
LVL 92

Accepted Solution

by:
objects earned 500 total points
ID: 35022499
there is no api, and all the methods people use just give an approximation.
0
 

Author Comment

by:MatrixStar
ID: 35022774
Thanks, I don't think, this will work well in multi threading environment.
0
 
LVL 59

Expert Comment

by:Kevin Cross
ID: 36935145
This question has been classified as abandoned and is closed as part of the Cleanup Program. See the recommendation for more details.
0

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

Suggested Solutions

I had a project requirement for a displaying a user workbench .This workbench would consist multiple data grids .In each grid the user will be able to see a large number of data. These data grids should allow the user to 1. Sort 2. Export the …
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now