1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/mobile/android/base/sync/DelayedWorkTracker.java Wed Dec 31 06:09:35 2014 +0100 1.3 @@ -0,0 +1,69 @@ 1.4 +/* This Source Code Form is subject to the terms of the Mozilla Public 1.5 + * License, v. 2.0. If a copy of the MPL was not distributed with this 1.6 + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 1.7 + 1.8 +package org.mozilla.gecko.sync; 1.9 + 1.10 +import org.mozilla.gecko.background.common.log.Logger; 1.11 + 1.12 +/** 1.13 + * A little class to allow us to maintain a count of extant 1.14 + * things (in our case, callbacks that need to fire), and 1.15 + * some work that we want done when that count hits 0. 1.16 + * 1.17 + * @author rnewman 1.18 + * 1.19 + */ 1.20 +public class DelayedWorkTracker { 1.21 + private static final String LOG_TAG = "DelayedWorkTracker"; 1.22 + protected Runnable workItem = null; 1.23 + protected int outstandingCount = 0; 1.24 + 1.25 + public int incrementOutstanding() { 1.26 + Logger.trace(LOG_TAG, "Incrementing outstanding."); 1.27 + synchronized(this) { 1.28 + return ++outstandingCount; 1.29 + } 1.30 + } 1.31 + public int decrementOutstanding() { 1.32 + Logger.trace(LOG_TAG, "Decrementing outstanding."); 1.33 + Runnable job = null; 1.34 + int count; 1.35 + synchronized(this) { 1.36 + if ((count = --outstandingCount) == 0 && 1.37 + workItem != null) { 1.38 + job = workItem; 1.39 + workItem = null; 1.40 + } else { 1.41 + return count; 1.42 + } 1.43 + } 1.44 + job.run(); 1.45 + // In case it's changed. 1.46 + return getOutstandingOperations(); 1.47 + } 1.48 + public int getOutstandingOperations() { 1.49 + synchronized(this) { 1.50 + return outstandingCount; 1.51 + } 1.52 + } 1.53 + public void delayWorkItem(Runnable item) { 1.54 + Logger.trace(LOG_TAG, "delayWorkItem."); 1.55 + boolean runnableNow = false; 1.56 + synchronized(this) { 1.57 + Logger.trace(LOG_TAG, "outstandingCount: " + outstandingCount); 1.58 + if (outstandingCount == 0) { 1.59 + runnableNow = true; 1.60 + } else { 1.61 + if (workItem != null) { 1.62 + throw new IllegalStateException("Work item already set!"); 1.63 + } 1.64 + workItem = item; 1.65 + } 1.66 + } 1.67 + if (runnableNow) { 1.68 + Logger.trace(LOG_TAG, "Running item now."); 1.69 + item.run(); 1.70 + } 1.71 + } 1.72 +} 1.73 \ No newline at end of file