import akka.actor.ActorRef;
import akka.japi.Pair;
import com.google.common.base.Preconditions;
-
+import java.io.Serializable;
import java.util.Collection;
import java.util.Comparator;
import java.util.SortedSet;
import java.util.TreeSet;
/**
- * This class will return First Entry
+ * This class will return First Entry.
*/
-public class LatestEntryRoutingLogic implements RoutingLogic{
+public class LatestEntryRoutingLogic implements RoutingLogic {
+
+ private final SortedSet<Pair<ActorRef, Long>> actorRefSet;
- private SortedSet<Pair<ActorRef, Long>> actorRefSet;
+ public LatestEntryRoutingLogic(Collection<Pair<ActorRef, Long>> entries) {
+ Preconditions.checkNotNull(entries, "Entries should not be null");
+ Preconditions.checkArgument(!entries.isEmpty(), "Entries collection should not be empty");
+
+ actorRefSet = new TreeSet<>(new LatestEntryComparator());
+ actorRefSet.addAll(entries);
+ }
- public LatestEntryRoutingLogic(Collection<Pair<ActorRef, Long>> entries) {
- Preconditions.checkNotNull(entries, "Entries should not be null");
- Preconditions.checkArgument(!entries.isEmpty(), "Entries collection should not be empty");
+ @Override
+ public ActorRef select() {
+ return actorRefSet.last().first();
+ }
- actorRefSet = new TreeSet<>(new LatestEntryComparator());
- actorRefSet.addAll(entries);
- }
+ private static class LatestEntryComparator implements Comparator<Pair<ActorRef, Long>>, Serializable {
+ private static final long serialVersionUID = 1L;
- @Override
- public ActorRef select() {
- return actorRefSet.last().first();
- }
+ @Override
+ public int compare(Pair<ActorRef, Long> o1, Pair<ActorRef, Long> o2) {
+ if (o1 == null && o2 == null) {
+ return 0;
+ }
+ if (o1 != null && o2 != null && o1.second() == null && o2.second() == null) {
+ return 0;
+ }
- private class LatestEntryComparator implements Comparator<Pair<ActorRef, Long>> {
+ if ((o1 == null || o1.second() == null) && o2 != null) {
+ return -1;
+ }
- @Override
- public int compare(Pair<ActorRef, Long> o1, Pair<ActorRef, Long> o2) {
- if(o1 == null && o2 == null) {
- return 0;
- }
- if(o1 == null && o2 != null) {
- return -1;
- }
- if(o1 != null && o2 == null) {
- return 1;
- }
-
- return o1.second().compareTo(o2.second());
+ if (o2 == null || o2.second() == null) {
+ return 1;
+ }
+ return o1.second().compareTo(o2.second());
+ }
}
-
- }
}