This repository has been archived on 2021-10-31. You can view files and clone it, but cannot push or open issues or pull requests.
PF3/hw2/Ex1/src/bintree/BinTreeCAS.java

65 lines
1.2 KiB
Java

package bintree;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
public class BinTreeCAS implements BinTree {
private static class Node {
final int value;
AtomicInteger occ;
AtomicReference<Node> left, right;
private Node(int value, int initOcc) {
this.value = value;
occ = new AtomicInteger(initOcc);
left = new AtomicReference<>();
left.set(null);
right = new AtomicReference<>();
right.set(null);
}
}
private final Node root = new Node(0, 0);
public void insert(int value) {
Node n = root;
while (true) {
int nval = n.value;
if (value == nval) {
n.occ.addAndGet(1);
return;
}
else if (value < nval) {
if (n.left.compareAndSet(null, new Node(value, 1))) {
return;
} else {
n = n.left.get();
}
}
else { // value > nval
if (n.right.compareAndSet(null, new Node(value, 1))) {
return;
} else {
n = n.right.get();
}
}
}
}
public int occurs(int value) {
Node n = root;
do {
int nval = n.value;
if (value == nval) {
return n.occ.intValue();
}
n = (value < nval) ? n.left.get() : n.right.get();
} while (n != null);
// value not found
return 0;
}
}