I am trying to implement a function that do a round robin on elements of a ConcurrentHashMap. For example, if there are {a, b, c} elements in the ConcurrentHashMap, the first time I call the function, it returns a, the second time, it returns b, the third time, it returns c, the forth time, it returns a.
private static Enumeration<Peer> nhEnmu;
private static final ConcurrentHashMap<String, Peer> peers;
private synchronized static Peer getNextPeer()
{
if (nhEnmu == null || !nhEnmu.hasMoreElements())
{
nhEnmu = peers.elements();
}
return nhEnmu.nextElement();
}
I implemented this function as above, however, the NoSuchElementException keeps poping out, I am wondering that is there anything wrong for using the elements() method? If it is not appropriate, what implementation should I adapt? Thank you!
The exception trace is as follows:
at Main$MsgProcessorThread.run(Main.java:119)
Exception in thread "Thread-1" java.util.NoSuchElementException at
java.util.concurrent.ConcurrentHashMap$HashIterator.nextEntry(ConcurrentHashMap.java:1266) at
java.util.concurrent.ConcurrentHashMap$ValueIterator.nextElement(ConcurrentHashMap.java:1297) at
control.Protocol.getNextPeer(Protocol.java:89)