From 34e2be945ea5fe877711ffc1985e43102e26b4c8 Mon Sep 17 00:00:00 2001 From: Menny Even Danan Date: Tue, 2 Jun 2015 21:35:27 -0400 Subject: moving JAVA implementations to JNI libs --- .../com/anysoftkeyboard/base/utils/GCUtils.java | 62 ++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 base/src/main/java/com/anysoftkeyboard/base/utils/GCUtils.java (limited to 'base/src') diff --git a/base/src/main/java/com/anysoftkeyboard/base/utils/GCUtils.java b/base/src/main/java/com/anysoftkeyboard/base/utils/GCUtils.java new file mode 100644 index 000000000..d22c72d4c --- /dev/null +++ b/base/src/main/java/com/anysoftkeyboard/base/utils/GCUtils.java @@ -0,0 +1,62 @@ +package com.anysoftkeyboard.base.utils; + +import android.text.format.DateUtils; +import android.util.Log; + +public class GCUtils { + private static final int GC_TRY_COUNT = 2; + // GC_TRY_LOOP_MAX is used for the hard limit of GC wait, + // GC_TRY_LOOP_MAX should be greater than GC_TRY_COUNT. + private static final int GC_TRY_LOOP_MAX = 5; + private static final long GC_INTERVAL = DateUtils.SECOND_IN_MILLIS; + private static final GCUtils sInstance = new GCUtils(); + private int mGCTryCount = 0; + + public static GCUtils getInstance() { + return sInstance; + } + + public boolean performOperationWithMemRetry(String TAG, MemRelatedOperation operation, boolean failWithException) { + reset(); + + boolean retry = true; + while (retry) { + try { + operation.operation(); + return true; + } catch (OutOfMemoryError e) { + Log.w(TAG, "WOW! No memory for operation... I'll try to release some."); + retry = tryGCOrWait(TAG, e); + if (!retry && failWithException) throw e; + } + } + return false; + } + + private void reset() { + mGCTryCount = 0; + } + + private boolean tryGCOrWait(String metaData, Throwable t) { + if (mGCTryCount % GC_TRY_COUNT == 0) { + System.gc(); + } + if (mGCTryCount > GC_TRY_LOOP_MAX) { + return false; + } else { + mGCTryCount++; + try { + Thread.sleep(GC_INTERVAL); + return true; + } catch (InterruptedException e) { + Log.e(metaData, "Sleep was interrupted."); + //ImeLogger.logOnException(metaData, t); + return false; + } + } + } + + public interface MemRelatedOperation { + void operation(); + } +} -- cgit v1.2.3