Last active
August 6, 2022 17:19
-
-
Save javieranton-zz/ca83c2a9baeeb447fd95bccd4f47ff77 to your computer and use it in GitHub Desktop.
Prevent GC crashes when processing too large strings too quickly
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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