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

57
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 (3851L/22K).

/** 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() {
    while (!up) {
      try {
        wait();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }

  public bool waitUntilUp(double timeout) {
    ret waitUntilUp(toMS(timeout));
  }
  
  public synchronized bool waitUntilUp(long timeout) {
    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/9
Text MD5: 71137175e33f19fca0e3ec29482b6082
Transpilation MD5: 16d13b0a95a38fc61e3b36195007f8ca
Author: stefan
Category:
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2021-09-24 21:57:51
Source code size: 1244 bytes / 57 lines
Pitched / IR pitched: No / No
Views / Downloads: 611 / 8784
Version history: 8 change(s)
Referenced in: #1000916 #1001224 #1001225 #1001226 #1001318 #1003674 #3000382