Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import kotlinx.atomicfu.AtomicRef;
- public class Solution implements AtomicCounter {
- private final ThreadLocal<Node> last;
- private final Node root; // root is initial value for last
- public Solution(){
- this.root = new Node();
- this.last = ThreadLocal.withInitial(() -> root);
- /*this.last = new ThreadLocal<>();
- this.last.set(root);*/
- }
- public int getAndAdd(int x) {
- int res;
- while(true){
- int upd = last.get().val.getValue();
- //System.out.println("Old: " + upd);
- res = upd + x;
- Node node = new Node();
- node.val.setValue(res);
- /*ThreadLocal<Node> node = ThreadLocal.withInitial(() -> new Node());
- node.get().val.setValue(upd);*/
- last.set(last.get().next.decide(node));
- if (last.get() == node){
- break;
- }
- }
- //System.out.println("Final res: " + res);
- return res;
- }
- private static class Node {
- private final AtomicRef<Integer> val = new AtomicRef<>(0);
- private final Consensus<Node> next = new Consensus<>();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement