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

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

mercurial