Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

61
LINES

< > BotCompany Repo | #1000781 // Flag class with listeners (incomplete)

JavaX fragment (include)

1  
/** this class is fully thread-safe */
2  
class Flag {
3  
  private boolean up;
4  
  private Trigger listeners = new Trigger();
5  
6  
  /** returns true if flag was down before */
7  
  public synchronized boolean raise() {
8  
    boolean result = doRaise();
9  
    if (result) {
10  
      listeners.trigger();
11  
      listeners = null;
12  
    }
13  
    return result;
14  
  }
15  
16  
  private synchronized boolean doRaise() {
17  
    if (!up) {
18  
      up = true;
19  
      notifyAll();
20  
      return true;
21  
    } else
22  
      return false;
23  
  }
24  
25  
  public synchronized void waitUntilUp() {
26  
    if (!up) {
27  
      try {
28  
        wait();
29  
      } catch (InterruptedException e) {
30  
        e.printStackTrace();
31  
      }
32  
    }
33  
  }
34  
35  
  public void onRaise(Runnable listener) {
36  
    if (!addListener(listener))
37  
      listener.run();
38  
  }
39  
40  
  private synchronized boolean addListener(Runnable listener) {
41  
    if (!up) {
42  
      listeners.addListener(listener);
43  
      return true;
44  
    } else
45  
      return false;
46  
  }
47  
48  
  public synchronized boolean isUp() {
49  
    return up;
50  
  }
51  
52  
  public String toString() {
53  
    return isUp() ? "up" : "down";
54  
  }
55  
56  
  // currently does a semi-active wait with latency = 50 ms
57  
  public void waitForThisOr(Flag otherFlag) {
58  
    while (!isUp() && !otherFlag.isUp())
59  
      MultiCoreUtil.sleep(50);
60  
  }
61  
}

download  show line numbers  debug dex  old transpilations   

Travelled to 13 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, gwrvuhgaqvyk, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tslmcundralx, tvejysmllsmz, vouqrxazstgt

No comments. add comment

Snippet ID: #1000781
Snippet name: Flag class with listeners (incomplete)
Eternal ID of this version: #1000781/1
Text MD5: 83018195c822c1c7aec9305d168dc9b2
Author: stefan
Category:
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2015-08-27 01:57:30
Source code size: 1307 bytes / 61 lines
Pitched / IR pitched: No / Yes
Views / Downloads: 623 / 555
Referenced in: [show references]