简体   繁体   中英

OutOfMemoryError by using java.util.Timer

Timer mTimer;

void scheduleSyncIn(int aSeconds){
    if (mTimer != null) {
        mTimer.cancel();
        mTimer = null;
    }
    mTimer = new Timer();
    TimerTask task = new TimerTask() {

        @Override
        public void run() {
           handleTimeout();
         }
    };

    if (request) {
        mTimer.schedule(task, aSeconds * 1000);
    }
}

method that is called by timer task

void handleTimeout(){
    Handler mainHandler = new Handler(mContext.getMainLooper());
    Runnable runnable = new Runnable(){

            @Override
            public void run() {
                sync(); //call the sync
            }
        };
        mainHandler.post(runnable);
    }

from this i got the following report from play store

java.lang.OutOfMemoryError: pthread_create (stack size 16384 bytes) failed: Try again
at java.lang.VMThread.create(Native Method)
at java.lang.Thread.start(Thread.java:1029)
at java.util.Timer$TimerImpl.<init>(Timer.java:192)
at java.util.Timer.<init>(Timer.java:367)
at java.util.Timer.<init>(Timer.java:387)
at java.util.Timer.<init>(Timer.java:394)
at com.example.Manager.scheduleSyncIn(Manager.java:66)
at com.example.Manager.scheduleSync(Manager.java:56)
at com.example.Manager.RequestDone(Manager.java:180)
com.example.Manager.Remote$GetMetaData.onPostExecute(Remote.java:338)
at com.example.Manager.Remote$GetMetaData.onPostExecute(Remote.java:1)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5137)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:611)
at dalvik.system.NativeStart.main(Native Method)

now i don't know why this error while i am cancel the timer and free it for GC every time before initialize. Thanks for any help.

I would recommend using Handler instead of Timer in android that it can cause memory leaks in your application.

sample:

  Handler mHandler;
  Runnable mRunnable;
  void scheduleSyncIn(int aSeconds){
      mHandler = new Handler();
      mRunnable = new Runnable() {

            @Override
            public void run() {
              mHandler.postDelayed(mRunnable, aSeconds);
            }
          };
      mHandler.postDelayed(mRunnable, aSeconds);

  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM