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

40
LINES

< > BotCompany Repo | #1032124 // SerializeComputations

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

Libraryless. Click here for Pure Java version (6332L/36K).

sclass SerializeComputations<A, B> {
  Map<A, Var<OKOrError<B>>> calculating = syncMap();
  new MultiSetMap<A, Thread> waitingFor;
  
  B get(A a, IF1<A, B> f) {
    ret get(a, () -> f.get(a));
  }

  B get(A a, IF0<B> f) {
    bool meCalc;
    Var<OKOrError<B>> var;
    synchronized {
      var = calculating.get(a);
      meCalc = var == null;
      
      if (meCalc) {
        var = new Var;
        calculating.put(a, var);
      } else
        waitingFor.put(a, currentThread());
    }
    
    if (meCalc) {
      OKOrError<B> b = okOrError(() -> f!);
      var.set(b);
      ret b.getMandatory();
    } else {
      try {
        waitUntilNotNull(var);
        ret var->getMandatory();
      } finally {
        synchronized {
          waitingFor.remove(a, currentThread());
          if (!waitingFor.containsKey(a))
            calculating.remove(a);
        }
      }
    }
  }
}

Author comment

Began life as a copy of #1032122

download  show line numbers  debug dex  old transpilations   

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

No comments. add comment

Snippet ID: #1032124
Snippet name: SerializeComputations
Eternal ID of this version: #1032124/11
Text MD5: dc0dfda23739f460c10dc6f43fd0c864
Transpilation MD5: 01c17d6a75ebecebb251938a01470071
Author: stefan
Category: javax / multi-threading
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2021-11-01 23:22:20
Source code size: 930 bytes / 40 lines
Pitched / IR pitched: No / No
Views / Downloads: 199 / 417
Version history: 10 change(s)
Referenced in: [show references]