I am creating a java.util.concurrent.ConcurrentSkipListSet
with a comparator. My comparator compares an Instant field in the object to determine the order. This is the comparator:
public int compare(myObj first, myObj second) {
if (first == null || first.getTime() == null) {
return 1;
}
if (second == null || second.getTime() == null) {
return -1;
}
if ( first.getTime().isBefore(second.getTime()) {
return -1;
}
else {
return 1;
}
}
When I use the above compartor 5/10 times it is stuck in an infinite loop. First is always after second , so the program always reach the else and return 1, however in some runs it just loops, it reaches the else but is just stuck constantly running the comparator... I can see this when I run in debug mode and also when adding extra logging. To clarify the 2 objects are not the same when it is stuck, so the issue isn't trying to add duplicated. When I switch isBefore to isAfter like so, I don't get that behaviour, it runs as expected each time. My question is why would this happen?
public int compare(myObj first, myObj second) {
if (first == null || first.getTime() == null) {
return 1;
}
if (second == null || second.getTime() == null) {
return -1;
}
if ( first.getTime().isAfter(second.getTime()) {
return 1;
}
else {
return -1;
}
}
Adding to the list implementation (boiled down for simplicity)
My concurrent skip set logic is very simple, I create the set with the compartor above, then myObj instant is initiated to now() + a predetermines number of minutes (hard coded so this calculation will not fail) then my obj is added to the concurrentskipset
private ConcurrentSkipListSet<MyObj> skipSetImpl= new ConcurrentSkipListSet<>(new MyObj.MyobjComp());
// added in a method, using Java Instant
foo.setTime( now.plus(60, ChronoUnit.SECONDS) );
this.skipSetImpl.add(foo); // add to concurrentSkipSet