Java – Is it possible to change Garbage Collection behavior in Java ME


I was wondering if it is possible to tweak the way garbage collector works on JavaMe in order to improve performance somehow(may reducing the number of passages)? I´ve seen some articles about it, but mostly directed Java SE and most of them says GC is highly dependant on the maker. How much would that be.

Best Solution

When the garbage collector is triggered is largely a mistery unless you have first hand knowledge of how the particular VM your application is running on was implemented and exactly how it was configured and customized for the specific phone you are using.

Calling java.lang.System.gc() is no guarantee that the garbage collector is triggered. It usually merely increases the probablility of the VM launching garbage collection very soon.

I have found that calling System.gc() 3 times consecutively in the same Thread but from 3 different methods tends to work reasonably well.

There are many ways to work around ineficiencies in the JavaME standard API implementations in order to reduce the amount of garbage you generate:

  • Extend ByteArrayOutputStream so you don't create a copy of the byte array when you want to access the data.

  • avoid calling StringBuffer.getChars() and StringBuffer.toString(). make your code work with StringBuffer offsets and lengths instead.

  • turn local buffers (byte[], StringBuffer...) into instance or static variables (and protect them with synchronized). Obviously, there is an overhead to doing this but it can prevent your application from freezing due to garbage collection too often.

  • Extend StringBuffer to avoid switching back and forth between String and StringBuffer : implement append(String, offset, length), parseInt(int), indexOf(String, index), replace(offset, StringBuffer, offset, length)...