summaryrefslogtreecommitdiffstats
path: root/mobile/android/services/src/main/java/org/mozilla/gecko/sync/DelayedWorkTracker.java
diff options
context:
space:
mode:
Diffstat (limited to 'mobile/android/services/src/main/java/org/mozilla/gecko/sync/DelayedWorkTracker.java')
-rw-r--r--mobile/android/services/src/main/java/org/mozilla/gecko/sync/DelayedWorkTracker.java69
1 files changed, 69 insertions, 0 deletions
diff --git a/mobile/android/services/src/main/java/org/mozilla/gecko/sync/DelayedWorkTracker.java b/mobile/android/services/src/main/java/org/mozilla/gecko/sync/DelayedWorkTracker.java
new file mode 100644
index 000000000..ddcb5411c
--- /dev/null
+++ b/mobile/android/services/src/main/java/org/mozilla/gecko/sync/DelayedWorkTracker.java
@@ -0,0 +1,69 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+package org.mozilla.gecko.sync;
+
+import org.mozilla.gecko.background.common.log.Logger;
+
+/**
+ * A little class to allow us to maintain a count of extant
+ * things (in our case, callbacks that need to fire), and
+ * some work that we want done when that count hits 0.
+ *
+ * @author rnewman
+ *
+ */
+public class DelayedWorkTracker {
+ private static final String LOG_TAG = "DelayedWorkTracker";
+ protected Runnable workItem = null;
+ protected int outstandingCount = 0;
+
+ public int incrementOutstanding() {
+ Logger.trace(LOG_TAG, "Incrementing outstanding.");
+ synchronized(this) {
+ return ++outstandingCount;
+ }
+ }
+ public int decrementOutstanding() {
+ Logger.trace(LOG_TAG, "Decrementing outstanding.");
+ Runnable job = null;
+ int count;
+ synchronized(this) {
+ if ((count = --outstandingCount) == 0 &&
+ workItem != null) {
+ job = workItem;
+ workItem = null;
+ } else {
+ return count;
+ }
+ }
+ job.run();
+ // In case it's changed.
+ return getOutstandingOperations();
+ }
+ public int getOutstandingOperations() {
+ synchronized(this) {
+ return outstandingCount;
+ }
+ }
+ public void delayWorkItem(Runnable item) {
+ Logger.trace(LOG_TAG, "delayWorkItem.");
+ boolean runnableNow = false;
+ synchronized(this) {
+ Logger.trace(LOG_TAG, "outstandingCount: " + outstandingCount);
+ if (outstandingCount == 0) {
+ runnableNow = true;
+ } else {
+ if (workItem != null) {
+ throw new IllegalStateException("Work item already set!");
+ }
+ workItem = item;
+ }
+ }
+ if (runnableNow) {
+ Logger.trace(LOG_TAG, "Running item now.");
+ item.run();
+ }
+ }
+} \ No newline at end of file