Wednesday, February 21, 2007

Please! Don't Thread Safe Everything!

Thread safe is good, but please, don't do it everywhere. Do it only when instances will be used concurrently by multiple threads. We have three reasons to say that.
  • Unnecessary synchronized method invocations (and synchronized blocks) can cause unnecessary blocking and unblocking of threads, which can hurt performance.

  • Immutable objects tend to be instantiated more often, leading to greater numbers of often short-lived objects that can increase the work of the garbage collector.

  • Synchronization gives rise to the possibility of deadlock, a severe performance problem in which your program appears to hang.
None of these performance setbacks are good excuses for neglecting to make classes that need to thread-safe so, but they do constitute good reasons not to make classes thread-safe unnecessarily.

1 comment:

Jessica said...

This is great--a very thorough discussion. Thanks.

One situation that needs to be taken care of regarding the thread safe issue could be producer/consumer.