Skip to content

Commit

Permalink
feat(net) : optimizing the sortPeers method
Browse files Browse the repository at this point in the history
  • Loading branch information
zeusoo001 committed Jun 21, 2024
1 parent d383177 commit e8e61fe
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,11 @@ private static void remove(PeerConnection peerConnection) {
}

public static synchronized void sortPeers() {
peers.sort(Comparator.comparingDouble(c -> c.getChannel().getAvgLatency()));
try {
peers.sort(Comparator.comparingDouble(c -> c.getChannel().getAvgLatency()));
} catch (Exception e) {
logger.warn("Sort peers failed. {}", e.getMessage());
}
}

public static PeerConnection getPeerConnection(Channel channel) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -135,4 +135,32 @@ public void testGetPeers() throws Exception {
Assert.assertEquals(2, peers.size());
}

@Test
public void testSortPeers() throws Exception {
PeerConnection p1 = new PeerConnection();
PeerConnection p2 = new PeerConnection();

List<PeerConnection> peers = new ArrayList<>();
peers.add(p1);
peers.add(p2);

Field field = PeerManager.class.getDeclaredField("peers");
field.setAccessible(true);
field.set(PeerManager.class, Collections.synchronizedList(peers));

PeerManager.sortPeers();

Channel c1 = new Channel();
c1.updateAvgLatency(100000L);
ReflectUtils.setFieldValue(p1, "channel", c1);

Channel c2 = new Channel();
c2.updateAvgLatency(1000L);
ReflectUtils.setFieldValue(p2, "channel", c2);

PeerManager.sortPeers();

Assert.assertEquals(PeerManager.getPeers().get(0), p2);
}

}

0 comments on commit e8e61fe

Please sign in to comment.