Does java.util.concurrent.Delayed really make me break equality / collation?

DelayQueue trying to use Java DelayQueue , I need to implement the Delayed interface, which requires the compareTo() method , "which provides the ordering that matches its getDelay method." . Of course, the intention is that DelayQueue can easily sort the objects in the queue, so that the next of its delay can be returned to any recipient.

Now I need to also remove objects from the queue ahead of time. I need to call delayQueue.remove(queuedObject) . This, of course, only works if the objects in the queue have the equals() method, which reflects their payload and not the completely unrelated remaining delay time.

As a result, compareTo() based on the remaining delay time, while equals() based on the payload for the objects in the queue, so they are incompatible, as it is "highly recommended" in javadoc Comparable .

Question: am I missing something or is it really a bit of a fad in DelayQueue design?

+8
java equals concurrency compareto
source share
2 answers

An accessible room for maneuver may be in the ambiguity of the requirement that this order be getDelay its getDelay method. What does constancy mean? Could this mean using getDelay values ​​as the primary order and using other attributes as a secondary ordering to break ties for objects with equivalent getDelay values? If so, you would be fine if the equals method requires the equality of the getDelay values ​​and all the attributes used when using the compareTo method to break the line, but does not require the equality of any other attributes. This really means that the Delayed class must have value semantics.

0
source share

The fact that the two objects are not sufficiently different to justify ranking one over the other does not mean that the objects are identical. As a simple example, you can sort strings using case-insensitive string comparisons, but consider only two strings as equivalent if their use in upper and lower case matches. By such standards, “FRED” and “Fred” would not be unequal, but would be undefiled relative to each other. I would suggest that it is more important to have equals to indicate semantic equivalence than to be “consistent” with compareTo .

0
source share

All Articles