Pure Danger Tech


navigation
home

JavaOne: Bill Pugh on Defective Java Code

06 May 2008

Bill did a fun talk on some common defective Java and how to fix it. Bill is the driving force behind FindBugs so it should not be surprising that he has a lot of depth and bad code to share.

He finds bugs and inspiration for bug detectors by watching bug databases for many popular open source projects and Sun itself. He also finds his students to be good bug generators. :) Once you find a bug, you can write a bug detector for FindBugs (or other easier tools like PMD or Jackpot) and look for it everywhere. Favorite quote: “When you find something stupid, there’s probably more of it lying around”.

Some bug types that he looked at:

  • Conversions and streams – methods that return -1 for EOF are tricky, unexpected EOF hard to test
  • Synchronization – don’t synchronize on String literals or autoboxed primitives (as they’re shared), don’t synchronize on a field changed in the synchronization, don’t synchronize on getClass() (as subclasses won’t be synching on same object)
  • DateFormat and friends aren’t thread safe – familiar to many already, just create new or use ThreadLocal
  • equals() with subclassing – whether to use instanceof check (can break symmetry) or getClass() comparison (can’t subclass with valid equals). Three kinds of common equality – object (no equals() needed), value (based on values in fields), or behavior (can’t distinguish based on behavior). Both instanceof() and getClass() can be useful but should protect yourself appropriately for subclassing.

Bill announced a new contest he’s running where you should send him a bug from your own application. He will write a detector to find more of it and run it on the code bases he tracks. Or you can send him a detector if you’re willing to do the work. The best detector wins $200. The best bug (most real bugs found) wins $100 (3 awarded).

This was a fun talk but I had hoped it would focus more on JSR 308 and 305 and how new annotations could be used to detect more bugs automatically.