Skip to content
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

fix(pd): Ensure range attribute thread safety #2641

Merged
merged 2 commits into from
Sep 25, 2024
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
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import com.google.common.collect.Range;

import org.apache.hugegraph.pd.grpc.Metapb.Graph;
import org.apache.hugegraph.pd.grpc.Metapb.Partition;

Expand All @@ -39,7 +41,7 @@ public class GraphCache {
private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@imbajin Can we improve and avoid this lombok.Data programming style in the future, which will cause internal members to be modified arbitrarily by external class?

private Map<Integer, AtomicBoolean> state = new ConcurrentHashMap<>();
private Map<Integer, Partition> partitions = new ConcurrentHashMap<>();
private RangeMap<Long, Integer> range = TreeRangeMap.create();
private RangeMap<Long, Integer> range = new SynchronizedRangeMap<Long, Integer>().rangeMap;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nice catch


public GraphCache(Graph graph) {
this.graph = graph;
Expand All @@ -59,4 +61,56 @@ public Partition addPartition(Integer id, Partition p) {
public Partition removePartition(Integer id) {
return partitions.remove(id);
}

public class SynchronizedRangeMap<K extends Comparable<K>, V> {

private final RangeMap<K, V> rangeMap = TreeRangeMap.create();
private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

public void put(Range<K> range, V value) {
lock.writeLock().lock();
try {
rangeMap.put(range, value);
} finally {
lock.writeLock().unlock();
}
}

public V get(K key) {
lock.readLock().lock();
try {
return rangeMap.get(key);
} finally {
lock.readLock().unlock();
}
}

public void remove(Range<K> range) {
lock.writeLock().lock();
try {
rangeMap.remove(range);
} finally {
lock.writeLock().unlock();
}
}

public Map.Entry<Range<K>, V> getEntry(K key) {
lock.readLock().lock();
try {
return rangeMap.getEntry(key);
} finally {
lock.readLock().unlock();
}
}

public void clear() {
lock.writeLock().lock();
try {
rangeMap.clear();
} finally {
lock.writeLock().unlock();
}
}
}

}
Loading