Skip to content

Fix the behavior of setCount in UnionFindSet when used concurrently #147

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 15, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions src/main/java/pascal/taie/util/collection/UnionFindSet.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

public class UnionFindSet<E> {
Expand All @@ -38,11 +39,11 @@ public class UnionFindSet<E> {
/**
* Number of disjoint sets.
*/
private int setCount;
private final AtomicInteger setCount = new AtomicInteger();

public UnionFindSet(Collection<E> elems) {
elems.forEach(elem -> entries.put(elem, new Entry(elem)));
setCount = entries.size();
setCount.set(entries.size());
}

/**
Expand All @@ -65,7 +66,7 @@ public boolean union(E e1, E e2) {
root2.parent = root1;
++root2.rank;
}
--setCount;
setCount.decrementAndGet();
return true;
}
}
Expand All @@ -90,7 +91,7 @@ public E findRoot(E e) {
* @return number of disjoint sets in this union-find set.
*/
public int numberOfSets() {
return setCount;
return setCount.get();
}

/**
Expand Down