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

61
LINES

< > BotCompany Repo | #1000915 // Simple static "Flag" class (thread-safe flagging, LIVE)

JavaX fragment (include) [tags: use-pretranspiled]

Libraryless. Click here for Pure Java version (125L/1K).

/** this class is fully thread-safe */
static class Flag implements Runnable {
  private boolean up;

  /** returns true if flag was down before (i.e. flag was actually raised right now) */
  public synchronized boolean raise() {
    if (!up) {
      up = true;
      notifyAll();
      return true;
    } else
      return false;
  }

  public synchronized void waitUntilUp() ctex {
    while (!up) {
      //try {
        wait();
      /*} catch (InterruptedException e) {
        e.printStackTrace();
      }*/
    }
  }

  public bool waitUntilUp(double timeout) {
    if (timeout == infinity()) {
      waitUntilUp();
      ret isUp();
    } else
      ret waitUntilUp(toMS(timeout));
  }
  
  public synchronized bool waitUntilUp(long timeout) ctex {
    if (!up) {
      //try {
        wait(timeout);
      /*} catch (InterruptedException e) {
        e.printStackTrace();
      }*/
    }
    ret isUp();
  }

  public synchronized boolean isUp() {
    return up;
  }
  
  bool get() { ret isUp(); }

  public String toString() {
    return isUp() ? "up" : "down";
  }

  // currently does a semi-active wait with latency = 50 ms
  public void waitForThisOr(Flag otherFlag) ctex {
    while (!isUp() && !otherFlag.isUp())
      Thread.sleep(50);
  }
  
  public void run() { raise(); }
}

Author comment

Began life as a copy of #1000782

download  show line numbers  debug dex  old transpilations   

Travelled to 24 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, ddnzoavkxhuk, fehiwqupcyrn, gwrvuhgaqvyk, imzmzdywqqli, ishqpsrjomds, jtubtzbbkimh, lhdilzshxjzv, lpdgvwnxivlt, lulzaavyztxj, mqqgnosmbjvj, onxytkatvevr, ppjhyzlbdabe, pyentgdyhuwx, pzhvpgtvlbxg, sawdedvomwva, tslmcundralx, tvejysmllsmz, vouqrxazstgt, wtqryiryparv, xrpafgyirdlv

No comments. add comment

Snippet ID: #1000915
Snippet name: Simple static "Flag" class (thread-safe flagging, LIVE)
Eternal ID of this version: #1000915/13
Text MD5: 2127596af4e0e11772430fe8ab57468b
Transpilation MD5: e3670f577eaa621f18de9745bf22e3ac
Author: stefan
Category:
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2022-03-25 22:46:42
Source code size: 1355 bytes / 61 lines
Pitched / IR pitched: No / No
Views / Downloads: 673 / 9039
Version history: 12 change(s)
Referenced in: [show references]