mobile/android/base/sync/DelayedWorkTracker.java

Thu, 22 Jan 2015 13:21:57 +0100

author
Michael Schloh von Bennewitz <michael@schloh.com>
date
Thu, 22 Jan 2015 13:21:57 +0100
branch
TOR_BUG_9701
changeset 15
b8a032363ba2
permissions
-rw-r--r--

Incorporate requested changes from Mozilla in review:
https://bugzilla.mozilla.org/show_bug.cgi?id=1123480#c6

michael@0 1 /* This Source Code Form is subject to the terms of the Mozilla Public
michael@0 2 * License, v. 2.0. If a copy of the MPL was not distributed with this
michael@0 3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
michael@0 4
michael@0 5 package org.mozilla.gecko.sync;
michael@0 6
michael@0 7 import org.mozilla.gecko.background.common.log.Logger;
michael@0 8
michael@0 9 /**
michael@0 10 * A little class to allow us to maintain a count of extant
michael@0 11 * things (in our case, callbacks that need to fire), and
michael@0 12 * some work that we want done when that count hits 0.
michael@0 13 *
michael@0 14 * @author rnewman
michael@0 15 *
michael@0 16 */
michael@0 17 public class DelayedWorkTracker {
michael@0 18 private static final String LOG_TAG = "DelayedWorkTracker";
michael@0 19 protected Runnable workItem = null;
michael@0 20 protected int outstandingCount = 0;
michael@0 21
michael@0 22 public int incrementOutstanding() {
michael@0 23 Logger.trace(LOG_TAG, "Incrementing outstanding.");
michael@0 24 synchronized(this) {
michael@0 25 return ++outstandingCount;
michael@0 26 }
michael@0 27 }
michael@0 28 public int decrementOutstanding() {
michael@0 29 Logger.trace(LOG_TAG, "Decrementing outstanding.");
michael@0 30 Runnable job = null;
michael@0 31 int count;
michael@0 32 synchronized(this) {
michael@0 33 if ((count = --outstandingCount) == 0 &&
michael@0 34 workItem != null) {
michael@0 35 job = workItem;
michael@0 36 workItem = null;
michael@0 37 } else {
michael@0 38 return count;
michael@0 39 }
michael@0 40 }
michael@0 41 job.run();
michael@0 42 // In case it's changed.
michael@0 43 return getOutstandingOperations();
michael@0 44 }
michael@0 45 public int getOutstandingOperations() {
michael@0 46 synchronized(this) {
michael@0 47 return outstandingCount;
michael@0 48 }
michael@0 49 }
michael@0 50 public void delayWorkItem(Runnable item) {
michael@0 51 Logger.trace(LOG_TAG, "delayWorkItem.");
michael@0 52 boolean runnableNow = false;
michael@0 53 synchronized(this) {
michael@0 54 Logger.trace(LOG_TAG, "outstandingCount: " + outstandingCount);
michael@0 55 if (outstandingCount == 0) {
michael@0 56 runnableNow = true;
michael@0 57 } else {
michael@0 58 if (workItem != null) {
michael@0 59 throw new IllegalStateException("Work item already set!");
michael@0 60 }
michael@0 61 workItem = item;
michael@0 62 }
michael@0 63 }
michael@0 64 if (runnableNow) {
michael@0 65 Logger.trace(LOG_TAG, "Running item now.");
michael@0 66 item.run();
michael@0 67 }
michael@0 68 }
michael@0 69 }

mercurial