Skip to content

Commit 2cef10c

Browse files
authored
Fix the behavior of setCount in UnionFindSet when used concurrently (#147)
1 parent a8b3982 commit 2cef10c

File tree

1 file changed

+5
-4
lines changed

1 file changed

+5
-4
lines changed

src/main/java/pascal/taie/util/collection/UnionFindSet.java

+5-4
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
import java.util.HashMap;
2727
import java.util.Map;
2828
import java.util.Set;
29+
import java.util.concurrent.atomic.AtomicInteger;
2930
import java.util.stream.Collectors;
3031

3132
public class UnionFindSet<E> {
@@ -38,11 +39,11 @@ public class UnionFindSet<E> {
3839
/**
3940
* Number of disjoint sets.
4041
*/
41-
private int setCount;
42+
private final AtomicInteger setCount = new AtomicInteger();
4243

4344
public UnionFindSet(Collection<E> elems) {
4445
elems.forEach(elem -> entries.put(elem, new Entry(elem)));
45-
setCount = entries.size();
46+
setCount.set(entries.size());
4647
}
4748

4849
/**
@@ -65,7 +66,7 @@ public boolean union(E e1, E e2) {
6566
root2.parent = root1;
6667
++root2.rank;
6768
}
68-
--setCount;
69+
setCount.decrementAndGet();
6970
return true;
7071
}
7172
}
@@ -90,7 +91,7 @@ public E findRoot(E e) {
9091
* @return number of disjoint sets in this union-find set.
9192
*/
9293
public int numberOfSets() {
93-
return setCount;
94+
return setCount.get();
9495
}
9596

9697
/**

0 commit comments

Comments
 (0)