summaryrefslogtreecommitdiffstats
path: root/mobile/android/services/src/main/java/org/mozilla/gecko/sync/DelayedWorkTracker.java
blob: ddcb5411c0cc5e22c47472a8cc504ad0236f8b44 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
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();
    }
  }
}