views:

110

answers:

2

Hi guys. I got a strange problem when I run my app on Nexus One, Android 2.2. In my app, I used a native .so lib, built under NDK. In Java code, I have 2 threads: one UI thread, one to run codes from native so lib, and then updates the UI with the result data. In C++ code, I have a global variable "int count", which records the times a specific method "myMethod" is called, and the count is increased by one every time "myMethod" is called. When I run my app in Nexus One, with Android 2.2, the strange problem occured. In my log, the count is 1, 2, 3, and then a message says "08-24 12:32:57.961: DEBUG/dalvikvm(19244): GC_FOR_MALLOC freed 267 objects / 13712 bytes in 48ms". After this GC_FOR_MALLOC event, my count is reset, starting from 1 again, and then 2, 3, 4...Then it seems that there are 2 threads running the same "myMethod", each outputs its own trace, mixed with each others trace randomly. For example, the trace can be

    1, 2, 3, GC_FOR_MALLOC, 1, 2, 3, 4, 5, GC_FOR_MALLOC, 4, 5, 6, GC_FOR_MALLOC, 6, 7...

When I run the same app with exactly the same code on Android Emulator, 2.1 or 2.2, the problem never showed up, and there are no GC_FOR_MALLOC event on emulator.

Some one met this problem before? Thank you for your help!

A: 

Maybe try using the volatile keyword on the variable? http://www.drdobbs.com/184403766

When do you instatiate the native class? Which thread calls the myMethod? Which reads the count? This may be due to compiler optimization. Would maybe explain why emulator running debug code wouldn't see the issue. Just a guess based on the provided info.

GrkEngineer
Thank you for your reply.When I run the same code within the same environment today, the problem never showed up, neither the GC_FOR_MALLOC event. It seems like a bug in dalvikvm? I'm not sure.
MaratSafinWang
A: 

It sounds like the garbage collector is sweeping the class that loaded your library, and it's being re-loaded (and re-setting your global variable) on subsequent calls. Where are you loading the library?

Marc