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

68
LINES

< > BotCompany Repo | #1033336 // PingSource

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

Libraryless. Click here for Pure Java version (7123L/40K).

// In the newest pinging system (with flag PingV3), a ping source
// is the object that "allows" some code to run.
// When that code calls ping(), the ping source's action (if defined)
// is triggered.

// This allows randomly interrupting code execution, for example.

sclass PingSource {
  // returns true if it slept
  settable volatile IF0<Bool> action;
  
  // optional description of this ping source
  S text;
  
  // optional thread pool that this ping source likes to run in
  ThreadPool threadPool;
  
  *() {}
  *(ThreadPool *threadPool) {}
  *(ThreadPool *threadPool, S *text) {}
  *(IF0<Bool> *action) {}

  // returns true if it slept
  final bool get() {
    var a = action;
    ret a != null && a!;
  }
  
  final void ping { 
    var a = action;
    if (a != null) a!;
  }
  
  void cancel {
    action = new Cancelled;
  }
  
  class Cancelled is IF0<Bool> {
    public Bool get() { throw new PingSourceCancelledException(PingSource.this); }
  }
  
  record noeq Encapsulated(Runnable r) is Runnable {
    run {
      //System.out.println("Encapsulated running: " + r);
      try {
        pingSource_tl().set(PingSource.this);
        //System.out.println("Ping source set");
        ping();
        r.run();
        //System.out.println("Done running");
      } finally {
        //System.out.println("Finally");
        pingSource_tl().set(null);
      }
    }
    
    toString { ret PingSource.this + ": " + r; }
  }
  
  void do(Runnable r) {
    if (r == null) ret;
    threadPool.acquireThreadOrQueue(new Encapsulated(r));
  }
  
  toString { S t = text; ret nempty(t) ? t : super.toString(); }
  
  ISleeper_v2 sleeper() { ret threadPool.sleeper(); }
}

download  show line numbers  debug dex  old transpilations   

Travelled to 4 computer(s): bhatertpkbcr, ekrmjmnbrukm, mowyntqkapby, mqqgnosmbjvj

No comments. add comment

Snippet ID: #1033336
Snippet name: PingSource
Eternal ID of this version: #1033336/35
Text MD5: 849a575b25154cabb0f69c1abf276a32
Transpilation MD5: 06ec60de52763821cc6ca88d76478062
Author: stefan
Category: javax
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2022-01-28 21:40:25
Source code size: 1746 bytes / 68 lines
Pitched / IR pitched: No / No
Views / Downloads: 312 / 549
Version history: 34 change(s)
Referenced in: #1034167 - Standard Classes + Interfaces (LIVE, continuation of #1003674)