Dienstag, 19. Oktober 2010

Beware Abstract Methods During Construction of Java Objects

It should be common knowledge, but it happens anyway: During constructing a Java object an abstract method is called. The called method relies on the values initialized in the derived object. The result: unexpected behaviour and often hard to find errors. So always remember: Never call abstract methods during construction of a Java object! Neitherin the constructor nor while initializen the instance variables!

The behaviour can be seen executing the following little test class:

abstract class Parent {

    int value;

    public Parent() {
        value = dangerousInitializer();
    }

    protected abstract int dangerousInitializer();

}

class Child extends Parent {

    int desiredValue = 42;

    @Override
    protected int dangerousInitializer() {
        return desiredValue;
    }

}

public class Test {
    public static void main(String[] args) {
        Child child = new Child();
        System.out.println("child.desiredValue=" + child.desiredValue);
        System.out.println("child.value=" + child.value);
    }
}

The result:
child.desiredValue=42
child.value=0

Java Performance: Division versus Bitshifting

Implementing high performance algorithms sometimes the question arises whether to uses division or bitshifting (for divisions by a power of two). I've done a little test if this really improves performance with jdk 1.6.0_13. The results show that data shifting indeed is considerably faster:

1000000000 usual divisions  took 1441.8 ms (use i / 2)
1000000000 divisions by bitshifting took 865.9 ms (use i >> 1)

I execute the divisions in a for loop, 10 executions per run (to decrease influence of loop overhead)...


Comments are welcome of course :-)
Today I start this blog with my first post! :-)

I needed a little helper method extracting the digits from a given integer. After searching for an existing utility method without success I created my own method I would like to share:

     public static int getDigit(int number, int digitPos) {
        return (number % 10 ^ (digitPos - 1)) / 10 ^ digitPos;
    }