tags:

views:

148

answers:

4

Is there any way to find out the number of objects that gets created? For example, If I need to find the number of objects that gets created for the below piece of code, how can I get it done? Code:

String [][] str = { {new String("A"),new String("B"),new String("C")}, {new String("D"),new String("E")} };
+3  A: 

Yes -- you can use a profiler, like Yourkit.

wsorenson
A: 

In this case you can just do

int numberOfObjects = 0;
for(String[] s: str)
{
    numberOfObjects += s.length;
}

Edit: nevermind I'm just really bad at everything forever...

faceless1_14
-1: I'm pretty sure this is not what he means. Besides, your code doesn't even give the right answer!
Stephen C
to whoever down voted what is wrong with this solution he asked for a very specific case where this solution works perfectly well.
faceless1_14
this is certainly not the way to ascertain the # of objects created in Java, and there are multiple problems with this approach:a) it could create more objectsb) it adds code in the same codebase as that which you're inspectingc) it is unlikely that it yields the correct answer even for this exampleto name a few..
wsorenson
The arrays themselves are objects and your code does not count them. In addition, the constructor of the String class may possibly create more objects.
Esko Luontola
Nope it doesn't. It doesn't count the objects implicitly created by `String` and the arrays themselves.
notnoop
Also, if the String class has not yet been loaded by the ClassLoader, that will cause lots of more objects to be created.
Esko Luontola
It also, doesn't handle cases where the array contains identical objects: your code would double count myStrRef `new String[] {myStrRef, myStrRef}`, even though it is a reference to one object.
notnoop
Yea thank you for the explanation. I have an overly simplistic view of Java sometimes. Not to mention misunderstanding the question entirely. I didn't even think about the ClassLoader and such.
faceless1_14
+1  A: 

Netbeans and Eclipse both have good profilers that will give you this information. This works if you can run your project in one of these IDE's.

Milhous
A: 

Here's a litle batch file (hoping your running windows) which enables you to walk through the heap of any java app running in a JDK vm, using JDK tools.

It dumps the heap using JMAP, and then runs a webserver using JHAT, then you can surf the (offline) heap :)

@echo off
if not [%1%]==[] goto map
cls
echo.
echo Gebruik: map.cmd [pid#]
echo.
echo ( JVM 6+ required. You're using : %JAVA_HOME% )
echo.
echo Which PID would you like to use?
echo.
jps -l
echo.
pause
exit /b

:map
if exist c:\jmap.txt del c:\jmap.txt
jmap -dump:file=c:\jmap.txt %1
echo.
echo about to start the web-server on port 8081
pause
start http://localhost:8081
start jhat -port 8081 c:\jmap.txt -J-mx512m
echo.
Houtman