Skip to content

Commit

Permalink
Bugfix: Task#compareTo(..) implementation is not constistent to #equa…
Browse files Browse the repository at this point in the history
…ls(..) implementation
  • Loading branch information
Petikoch committed Jan 9, 2015
1 parent 567f09d commit b75a482
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 7 deletions.
2 changes: 1 addition & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ apply plugin: 'maven-publish'
// "incubating"
apply plugin: 'jacoco'

version = '1.0.x-SNAPSHOT'
version = '1.0.1'
ext.artifactGroupId = 'ch.petikoch.libs'
ext.description = 'A little java 7+ standalone library using a "task wait for graph" model to detect deadlocks'

Expand Down
10 changes: 8 additions & 2 deletions src/main/java/ch/petikoch/libs/jtwfg/Task.java
Original file line number Diff line number Diff line change
Expand Up @@ -95,10 +95,16 @@ public String toString() {

@Override
public int compareTo(final Task<T> other) {
if (this.getId() instanceof Comparable && other.getId() instanceof Comparable) {
if ((this.getId() instanceof Comparable) &&
(other.getId() instanceof Comparable) &&
(this.getId().getClass().isAssignableFrom(other.getId().getClass()))) {
//noinspection unchecked
return ((Comparable) this.getId()).compareTo(other.getId());
}
return 0;
if (this.equals(other)) {
return 0; // "consistent" to equals
} else {
return -1; // "consistent" to equals
}
}
}
18 changes: 14 additions & 4 deletions src/test/groovy/ch/petikoch/libs/jtwfg/TaskTest.groovy
Original file line number Diff line number Diff line change
Expand Up @@ -62,24 +62,34 @@ class TaskTest extends Specification {
result == 1
}

def 'compareTo: returns 0 on types not implementing comparable'() {
def 'compareTo: behaviour on types not implementing comparable consistent to equals'() {
given:
def taskId1 = new CustomTaskId('t1')
def equalTaskId1 = new CustomTaskId('t1')
def taskId2 = new CustomTaskId('t2')
def task1 = new Task<CustomTaskId>(taskId1)
def equalTask1 = new Task<CustomTaskId>(equalTaskId1)
def task2 = new Task<CustomTaskId>(taskId2)

when:
def result = task1.compareTo(task2)
def result = task1.compareTo(equalTask1)
then:
result == 0

when:
result = equalTask1.compareTo(task1)
then:
result == 0

when:
result = task2.compareTo(task1)
result = task1.compareTo(task2)
then:
result == -1

when:
result = task2.compareTo(task1)
then:
result == 0
result == -1
}

@CompileStatic
Expand Down

0 comments on commit b75a482

Please sign in to comment.