Dear Experts,
It appears that we've found what I suspect is some kind of optimization
in Android that actually turns into a pretty nasty memory leak (BTW this
is under 2.2 since that is the project target):
Short version:
The docs for JSONTokener claims:
http://developer.android.com/reference/org/json/JSONTokener.html
"The returned string shares its backing character array with this
tokener's input string. If a reference to the returned string may be
held indefinitely, you should use new String(result) to copy it first to
avoid memory leaks.", BUT:
String original = hugeJsonObject.optString("name");
String dup = new String(original); // Still keeps reference!
Long version:
For reason beyond our control, we are forced to fetch *HUGE* amounts of
JSON data to extract what we actually need and we noted that the memory
ran out pretty quickly, due to the fact that the few data we actually
extract still keep the whole original JSON string around as that is
where the token was stored. Hence, we first tried the above code which
appeared to be a simple fix.
HOWEVER, using the Memory Analyser we could easily see that there was
STILL a reference around to the original huge string!
Workaround: // Verbose for clarity
byte[] tmp = original.getBytes();
String dup = new String(tmp);
This correctly removes the reference. Presumably this problem applies to
many more cases that are less obvious, but for our particular case the
leak was so huge that it just couldn't be written off as general java
leaks.
I hope this helps someone else!
Best / Jonas
--
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en