Skip to content

Instantly share code, notes, and snippets.

@javieranton-zz
Last active August 6, 2022 17:19
Show Gist options
  • Save javieranton-zz/ca83c2a9baeeb447fd95bccd4f47ff77 to your computer and use it in GitHub Desktop.
Save javieranton-zz/ca83c2a9baeeb447fd95bccd4f47ff77 to your computer and use it in GitHub Desktop.
Prevent GC crashes when processing too large strings too quickly
/**
* handles manual calls to GC + pause in case too much memory is being allocated too quickly to Strings in iOS
*/
public class StringThrottle {
private static long lastTimeSafeStringCreated = 0;
private static long accumulatedSizeInLast4Secs = 0;
private static int SafeStringDetectionPeriod = 4000;
private static int SafeStringPostGCSleep = 400;
private static int MaxSafeStringSizeB4GC = 5000000;
/**
* Calls GC and pauses if needed
* @param string
*/
public static void run(String string){
if(com.codename1.ui.CN.getPlatformName().equals("ios")) {
if (lastTimeSafeStringCreated == 0)
lastTimeSafeStringCreated = System.currentTimeMillis();
if (System.currentTimeMillis() - lastTimeSafeStringCreated < SafeStringDetectionPeriod)
accumulatedSizeInLast4Secs += string.length();
else
accumulatedSizeInLast4Secs = string.length();
if (accumulatedSizeInLast4Secs > MaxSafeStringSizeB4GC) {
accumulatedSizeInLast4Secs = 0;
System.gc();
try {
Thread.sleep(SafeStringPostGCSleep);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
lastTimeSafeStringCreated = System.currentTimeMillis();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment