package com.datdo.mobilib.util;

import java.util.ArrayList;
import java.util.List;

/**
 * <pre>
 * TBD
 * </pre>
 */
public class MblSerializer {

    /**
     * <pre>
     * TBD
     * </pre>
     */
    public static interface Task {
        public void run(Runnable finishCallback);
    }

    private final List<Task>    mTasks              = new ArrayList<Task>();
    private boolean             mIsRunning          = false;
    private final Runnable      mFinishCallback     = new Runnable() {
        @Override
        public void run() {
            mIsRunning = false;
            runNextTask();
        }
    };

    private void runNextTask() {
        synchronized (this) {
            if (!mIsRunning && !mTasks.isEmpty()) {
                mIsRunning = true;
                // post to main thread to prevent StackOverFlow
                MblUtils.getMainThreadHandler().post(new Runnable() {
                    @Override
                    public void run() {
                        mTasks.remove(0).run(mFinishCallback);
                    }
                });
            }
        }
    }

    /**
     * <pre>
     * TBD
     * </pre>
     * @param task
     */
    public void run(Task task) {
        synchronized (this) {
            mTasks.add(task);
            runNextTask();
        }
    }

    /**
     * <pre>
     * TBD
     * </pre>
     * @param task
     * @return
     */
    public boolean cancel(Task task) {
        synchronized (this) {
            return mTasks.remove(task);
        }
    }

    /**
     * <pre>TBD</pre>
     */
    public void cancelAll() {
        synchronized (this) {
            mTasks.clear();
        }
    }
}

@@ -657,133 +657,8 @@
 ) %7B%0A
-        synchronized (this) %7B%0A            if (!mIsRunning && !mTasks.isEmpty()) %7B%0A                mIsRunning = true;%0A        
     
@@ -717,24 +717,16 @@
         
-       
- 
 MblUtils
@@ -787,65 +787,204 @@
     
-        @Override%0A                    public void run() %7B
+@Override%0A            public void run() %7B%0A                synchronized (MblSerializer.this) %7B%0A                    if (!mIsRunning && !mTasks.isEmpty()) %7B%0A                        mIsRunning = true;
 %0A   
@@ -1082,18 +1082,16 @@
        %7D
-);
 %0A       
@@ -1089,32 +1089,32 @@
 %7D%0A            %7D%0A
-
         %7D%0A    %7D%0A
@@ -1098,32 +1098,34 @@
      %7D%0A        %7D
+);
 %0A    %7D%0A%0A    /**%0A

Fix bug of Serializer: task list is empty when it reaches main thread, which causes IndexOutOfBoundsException