J1 Session-Blog: Return of the Puzzlers (Schlock and Awe)
Dressed in boiler suites, Joshua Bloch (Google Inc.) and Neal Gafter (Microsoft) put on quite a show in which they present a series of traps to be avoided in the Java language…
Joshua Bloch (Google Inc.) and Neal Gafter (Microsoft)
- First problem: What does Boolean (Strings) do? Answer: Depends on the value of a particular system property – which is obviously completely horrible.
- Second problem: Overriding addAll/add of a HashSet is dangerous. Something we should all know because (for example) addAll may be implemented in terms of add. Answer is to create a so-called forwarding set, in which the inhertance characteristics of the implementation are defined by us. A class whose self-use patterns are not explicitly defined and documented should not be inherited from. Google collections provides a suite of forwarding classes.
- Third problem: Unpredictable behaviour caused by invoking a public (overridable) method in a constructor. Apparently Brian Goetz has made this mistake.
- Fourth problem: Searching which depends on a comparator is broken. In the example the comparator is broken because autoboxed integers cannot be tested for equality with. In addition, Comparator must implement total ordering, which in this example is broken because of the auto-boxing.
- Fifth problem: Initialization error caused by invoking enum constructor when a static variable has not been initialized.
- Sixth problem: Memory leak caused by assigning a large number of values to non-static thread locals. Thread local contains a weak hashmap. This is a complicated one to follow. One obvious moral: Don’t use non-static inner classes.
- Seventh problem: Problem caused when two versions of a class contain different constant definitions. Contants are inlined in Java. However, null is not considered a constant in this sense.
Overall: As we’d expect, nasty little problems which are likely to occur at some point in the developer’s life. Bloch suggests using “FindBugs”, which will apparently detect all of the above problems.

