Name Your Syncrhonization Objects
A not-used-enough feature of Java is the ability to set the name of a thread. Simply pass the name to the thread’s constructor, or call the Thread.setName() method. The nice thing about this is that when you’re looking at the thread list in a debugger, the names of the threads will be displayed rather than some random identifier generated by the JVM or debugger. This is a boon for sanity. But what about synchronization objects?
As Joshua Bloch recommends in Effective Java, it’s a good idea to favor the private lock object idiom over the more typical practice of sprinkling your methods with synchronized keywords. Now, most examples you’ll find just create a new Object for the private lock:
private Object lock = new Object();
That’s fine, but some debuggers, especially Eclipse will also show the locks that each thread holds and which lock they’re waiting for. If you just use a plain old Object, the debugger’s output won’t be very descriptive. Since the debugger just uses the toString() method to display the lock object, we could just use that to give the lock a name. I wish their was an object with the toString() method already implemented…
private Object lock = new String("My Lock");
The important thing here is to make sure you create a NEW string instance. If you just use a string literal, it will be taken from the string pool and, if you’re unlucky, your lock may get used and possibly locked by someone else. Not very private.
Anyway, the result is nice, readable lock names that really help when tracking down deadlocks.