Advertisement
Guest User

universal-dich2

a guest
Nov 13th, 2019
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.17 KB | None | 0 0
  1. import kotlinx.atomicfu.AtomicRef;
  2.  
  3.  
  4. public class Solution implements AtomicCounter {
  5. private final ThreadLocal<Node> last;
  6. private final Node root; // root is initial value for last
  7.  
  8. public Solution(){
  9. this.root = new Node();
  10. this.last = ThreadLocal.withInitial(() -> root);
  11. /*this.last = new ThreadLocal<>();
  12. this.last.set(root);*/
  13. }
  14.  
  15. public int getAndAdd(int x) {
  16. int res;
  17. while(true){
  18. int upd = last.get().val.getValue();
  19. //System.out.println("Old: " + upd);
  20. res = upd + x;
  21. Node node = new Node();
  22. node.val.setValue(res);
  23. /*ThreadLocal<Node> node = ThreadLocal.withInitial(() -> new Node());
  24. node.get().val.setValue(upd);*/
  25. last.set(last.get().next.decide(node));
  26. if (last.get() == node){
  27. break;
  28. }
  29. }
  30. //System.out.println("Final res: " + res);
  31. return res;
  32. }
  33.  
  34. private static class Node {
  35. private final AtomicRef<Integer> val = new AtomicRef<>(0);
  36. private final Consensus<Node> next = new Consensus<>();
  37. }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement