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

32
LINES

< > BotCompany Repo | #1035562 // PairCollector - concurrent collector for 2 objects with overridable & swappable complete() function

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

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

1  
import java.lang.invoke.VarHandle;
2  
import java.lang.invoke.MethodHandles;
3  
4  
// assumes that each set function is called only once
5  
sclass PairCollector<A, B> {
6  
  volatile A a;
7  
  volatile B b;
8  
  volatile int counter;
9  
  
10  
  // statically get var handles
11  
  private static final VarHandle vhA, vhB, vhCounter;
12  
  static ctex {
13  
    var l = MethodHandles.lookup();
14  
    vhA = l.findVarHandle(PairCollector.class, "a", O);
15  
    vhB = l.findVarHandle(PairCollector.class, "b", O);
16  
    vhCounter = l.findVarHandle(PairCollector.class, "counter", int.class);
17  
  }
18  
  
19  
  void setA(A a) { this.a = a; incCounter(); }
20  
  void setB(B b) { this.b = b; incCounter(); }
21  
  
22  
  IVF1<A> setterForA() { ret a -> setA(a); }
23  
  IVF1<B> setterForB() { ret b -> setB(b); }
24  
  
25  
  private void incCounter() {
26  
    if (((int) vhCounter.getAndAdd(this, 1))+1 == 2)
27  
      complete(a, b);
28  
  }
29  
  
30  
  // can override or swap
31  
  swappable void complete(A a, B b) {}
32  
}

download  show line numbers  debug dex  old transpilations   

Travelled to 3 computer(s): elmgxqgtpvxh, mowyntqkapby, mqqgnosmbjvj

No comments. add comment

Snippet ID: #1035562
Snippet name: PairCollector - concurrent collector for 2 objects with overridable & swappable complete() function
Eternal ID of this version: #1035562/11
Text MD5: 14311b666f416b8e2cc16bb23f836290
Transpilation MD5: d9bdac352b1794c567bb83f8d576fc77
Author: stefan
Category: javax / parallelism
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2022-06-17 00:26:12
Source code size: 949 bytes / 32 lines
Pitched / IR pitched: No / No
Views / Downloads: 105 / 177
Version history: 10 change(s)
Referenced in: [show references]