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

52
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 (2126L/14K).

/** 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 synchronized void waitUntilUp(long timeout) {
    if (!up) {
      try {
        wait(timeout);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }

  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/5
Text MD5: e2375c3ed581a07f4f6b09f806201b34
Transpilation MD5: 320216ebc467bcbda6113bb00656b7ca
Author: stefan
Category:
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2019-09-13 00:12:36
Source code size: 1136 bytes / 52 lines
Pitched / IR pitched: No / No
Views / Downloads: 559 / 8560
Version history: 4 change(s)
Referenced in: [show references]

Formerly at http://tinybrain.de/1000915 & http://1000915.tinybrain.de