1

I'm porting a game to Android (there's a lot of code and very little of it is mine), and DalvikVM is telling me (through LogCat) all about the garbage collection. At some point in the code, I get a stream of "GC freed x objects / x ms" messages, basically informing me that ~150,000 objects have just been deleted and it's taking a full second.

I want to know where these came from! I am pretty sure I'm not creating that many objects intentionally.

So, is there a way to get... basically the opposite of that message? Something that prints a log message when any object is created?

That way I could step over the code, checking how many messages are generated, and seeing which parts of code are generating the objects. I suspect some form of object creation in part of a loop, but if possible this would be an easy way to tell for sure.

Any ideas?

1 Answers1

0

Try this, it wil help you,

The Allocation Instrumenter is a Java agent written using the java.lang.instrument API and ASM. Each allocation in your Java program is instrumented; a user-defined callback is invoked on each allocation.

In order to write your own allocation tracking code, you have to implement the Sampler interface and pass an instance of that to AllocationRecorder.addSampler():

AllocationRecorder.addSampler(new Sampler() {
public void sampleAllocation(int count, String desc,
  Object newObj, long size) {
  System.out.println("I just allocated the object " + newObj + 
    " of type " + desc + " whose size is " + size);
  if (count != -1) { System.out.println("It's an array of size " + count); }
}

});

You can also use the allocation instrumenter to instrument constructors of particular classes. You do this by instantiating a ConstructorCallback and passing it to ConstructorInstrumenter.instrumentClass()

try {
  ConstructorInstrumenter.instrumentClass(
      Thread.class, new ConstructorCallback<Thread>() {
        @Override public void sample(Thread t) {
          System.out.println("Instantiating a thread");
        }
      });
} catch (UnmodifiableClassException e) {
  System.out.println("Class cannot be modified");
}

The Source Code of Project is Available Here

https://code.google.com/p/java-allocation-instrumenter/

In android by the solution given above and This is also possible using the ddms tool which has allocation tracker that comes with Android. You can start tracking allocations of all objects along with stack traces of where they were allocated. However, this tool can produce a -lot- of information and the particular information you want is not always easy to parse or find. If you have a version for the Sun JVM, I would recommend using the tools Kai mentioned, they are a lot more developed. If you have to do it in Android, using the allocation tracker will give you a start.

Umer Kiani
  • 3,783
  • 5
  • 36
  • 63