diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmSyncService.java b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmSyncService.java index 34e9c04c8..222285929 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmSyncService.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmSyncService.java @@ -12,6 +12,8 @@ import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Queue; +import java.util.concurrent.Semaphore; +import java.util.concurrent.atomic.AtomicInteger; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.ByteArrayBody; @@ -112,8 +114,10 @@ public final class ActFmSyncService { } private final List failedPushes = Collections.synchronizedList(new LinkedList()); - Thread pushRetryThread = null; - Runnable pushRetryRunnable; + private Thread pushRetryThread = null; + private Runnable pushRetryRunnable; + private final AtomicInteger taskPushThreads = new AtomicInteger(0); + private Semaphore waiter = null; public void initialize() { initializeRetryRunnable(); @@ -135,9 +139,17 @@ public final class ActFmSyncService { new Thread(new Runnable() { @Override public void run() { + taskPushThreads.incrementAndGet(); // sleep so metadata associated with task is saved AndroidUtilities.sleepDeep(1000L); pushTaskOnSave(model, setValues); + synchronized(ActFmSyncService.this) { + if (taskPushThreads.decrementAndGet() == 0) { + if (waiter != null) { + waiter.release(); + } + } + } } }).start(); } @@ -235,6 +247,23 @@ public final class ActFmSyncService { } } + public void waitUntilEmpty() { + synchronized(this) { + if (taskPushThreads.get() > 0) + waiter = new Semaphore(0); + else + return; + } + try { + waiter.acquire(); + } catch (InterruptedException e) { + // Ignored + } + synchronized(this) { + waiter = null; + } + } + // --- data push methods /** diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmSyncV2Provider.java b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmSyncV2Provider.java index d3b4f085d..4633c1c39 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmSyncV2Provider.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmSyncV2Provider.java @@ -118,6 +118,7 @@ public class ActFmSyncV2Provider extends SyncV2Provider { startTagFetcher(callback, finisher); + actFmSyncService.waitUntilEmpty(); startTaskFetcher(manual, callback, finisher); callback.incrementProgress(50); @@ -255,6 +256,7 @@ public class ActFmSyncV2Provider extends SyncV2Provider { fetchTagData(tagData, noRemoteId, manual, callback, finisher); if(!noRemoteId) { + actFmSyncService.waitUntilEmpty(); fetchTasksForTag(tagData, manual, callback, finisher); fetchUpdatesForTag(tagData, manual, callback, finisher); }