Wednesday, October 20, 2010

Java signal handler implementation

Here is a Java signal handler implementation. The signal will be handled even though Thread.sleep is running.
import sun.misc.Signal;
import sun.misc.SignalHandler;

public class Test
{
   public static void main(String[] args)
   {
       SignalHandler signalHandler = new SignalHandler() {
           public void handle(Signal signal) {
               System.err.println("Exiting because of signal: " + signal);
               System.exit(1);
           }
       });
       Signal.handle(new Signal("TERM"), signalHandler);
       Signal.handle(new Signal("INT"), signalHandler);

       try {
           Thread.sleep(50000);
       }
       catch (InterruptedException e) {
           System.err.println("Interrupted");
       }
   }
}

Tuesday, June 29, 2010

Java Comparable and equals() implementation

It is strongly recommended (though not required) that the natural ordering of a class (compareTo() method) be consistent with the equals() method (see java.lang.Comparable). The best way to keep them consistent, is to implement the equals() method as a call to the compareTo() method. This will increase the maintainability of the code: if any new fields are added to the class in the future, they will only have to be added to the compareTo() method, the equals() method will not have to be changed. When calling compareTo() from equals(), we need to be careful, because e.compareTo(null) should throw a NullPointerException even though e.equals(null) returns false.
public class ComparableExample implements Comparable<ComparableExample>
{
    private int number;
    private boolean bool;
    private String str;
    private Object obj;
    
    @Override
    public boolean equals(Object o)
    {
        if (null == o) { return false; }
        if (this == o) { return true; }
        if ( ! (o instanceof ComparableExample) ) { return false; }

        return 0 == compareTo((ComparableExample)o);
    }

    public int compareTo(ComparableExample that)
    {
        final int BEFORE = -1;
        final int EQUAL  = 0;
        final int AFTER  = 1;

        if (null == that) { throw new NullPointerException(getClass().getSimpleName() + ".compareTo() called with a null parameter"); }
        if (this == that) { return EQUAL; }

        int result = EQUAL;
        if (EQUAL == result) { result = (this.number < that.number ? BEFORE : (this.number > that.number ? AFTER : EQUAL)); }
        if (EQUAL == result) { result = (this.bool ? (that.bool ? EQUAL : AFTER) : (that.bool ? BEFORE : EQUAL)); }
        if (EQUAL == result) { result = (null == this.str ? (null == that.str ? EQUAL : BEFORE) : this.str.compareTo(that.str)); }
        if (EQUAL == result) { result = (null == this.obj ? (null == that.obj ? EQUAL : BEFORE) : this.obj.compareTo(that.obj)); }
        return result;
    }
}