Rob Smyth

Saturday, 23 February 2008

Threaded Applications Do Become Unstiched

A design defect that I keep coming across is the overuse of threads in applications. The worst case as several years ago when I came across code that used threads as a type of queue. That application crashed when the number threads got to a few thousand threads. More recently an application became much faster and more stable when the design was changed to remove all threads.

Using threads causes:
  • Application speed problems due to inherent delays in inter-thread communications and the inherent wait/sleeps that will creep in.
  • Require thread safe objects.
  • Leads to complex design which will lower code health.
  • Not deterministic.
The alternative is to make all slow calls asynchronous. No sleeps, no loops waiting for events. For timing use a timer in the same thread. The Windows UI thread is okay as you are never going to wait. Use call backs (e.g. delegates). Always do what is required when required.

When the design is changed to remove the threads the design becomes simpler (and hence the code healthier). Of course the change is done to eliminate intermittent defects (product health) which do disappear when the threads are removed.

Threads are added to code either because:
  • The future impact on the code health (the cost of that design) is not understood.
  • The alternative design approach is not known.
  • There is a fear of processing time to do what is required. You have no choice anyway as you must do what is required as "it is required" :-). If you use a thread it will just take longer anyway.
But, threads are not totally avoidable as our applications must interact with third party APIs. Only use threads to call to slow third party API synchronous methods. e.g. OS file call 'Open'.

If you have threads in your application, get rid of them. You are probably already having to update code to make it thread safe. If so, you just adding complexity as a design defect deodorant. The increased complexity will lead to more defects ... sound familiar?

No comments: