【发布时间】:2014-10-25 16:14:45
【问题描述】:
我在这里编写了一个修改后的 Kademlia P2P 系统,但我在这里描述的问题与原始系统的实现非常相似。
那么,实现 k-Bucket 最有效的方法是什么?对我来说重要的是访问时间、并行性(读写)和内存消耗。
想过用 ConcurrentLinkedQueue 和 ConcurrentHashMap 来做这件事,但那是相当多余和讨厌的,不是吗?
目前我只是在同步一个 LinkedList。
这是我的代码:
import java.util.LinkedList;
class Bucket {
private final LinkedList<Neighbour> neighbours;
private final Object lock;
Bucket() {
neighbours = new LinkedList<>();
lock = new Object();
}
void sync(Neighbour n) {
synchronized(lock) {
int index = neighbours.indexOf(n);
if(index == -1) {
neighbours.add(n);
n.updateLastSeen();
} else {
Neighbour old = neighbours.remove(index);
neighbours.add(old);
old.updateLastSeen();
}
}
}
void remove(Neighbour n) {
synchronized(lock) {
neighbours.remove(n);
}
}
Neighbour resolve(Node n) throws ResolveException {
Neighbour nextHop;
synchronized(lock) {
int index = neighbours.indexOf(n);
if(index == -1) {
nextHop = neighbours.poll();
neighbours.add(nextHop);
return nextHop;
} else {
return neighbours.get(index);
}
}
}
}
请不要怀疑,我已经实施了另一个邻居驱逐流程。
【问题讨论】: