Saturday, January 13, 2007

6 Tips for Java Threads

A while back I replied to a message on the Java Posse newsgroup entitled "Threads are EVIL". The poster was having trouble with Java threads, so in addition to recommending Java Thread Programming and Java Concurrency in Practice, I summarised the basics in the following tips.

#1 - Know what each of your threads does, and which threads can be inside which methods
...You can use asserts to check the names of executing threads in sensitive methods.

#2 - Know which variables are accessed by multiple threads, and which lock guards them
...Brian Goetz recommends annotating/commenting your variables to describe how they are guarded. But the best way to simplify this job is to avoid variables - use immutable classes wherever you can. (They're automatically threadsafe, very fast, and easy to code.)

#3 - Remember it's not enough to synchronize the writes to a shared variable
...You also have to synchronize the reads with the same lock.

#4 - Don't be afraid of the synchronized keyword
...It is NOT evil. Do be afraid however of large stacks of code inside a synchronized block/method. If you find one, take out the bits that don't need to be synchronized and/or split it up into smaller synchronized blocks.

#5 - Avoid nesting locks (ie. synchronized within synchronized)
...Try to think of another way to do it. (There are ways to get away with it, but you're asking for trouble later down the road.)

#6 - Keep it SIMPLE
...Don't do with 2 threads what you can do with 1. (Unless you get a measurable performance improvement by parallel processing CPU-intensive or IO-blocking code.)

No comments:

Post a Comment