|Developer Diary · You Heard It Here First · 7 December 2003|
|Dread of Threads|
Using multiple threads in an application leads to a unique set of problems. If a thread conflict occurs the bug can be intermittent and usually does not trigger an exception of any kind making it virtually untraceable. Yesterday I spent hours trying to figure out a strange error that had plagued our application on and off for at least six months. What would happen is that occasionally when the user went to a particular screen all or part of it would turn completely blue and the normal controls were not there. The other parts of the interface would continue to work fine. There was no exception of any kind being thrown. Bugs like this can make you tear your hair out because there is no obvious way to resolve them, especially since the error usually occurred only in a Linux environment rather than the Windows environment I use most of the time so I could not reliably reproduce it.
Eventually I figured it out: the program was calling into the Swing library from an independent thread and causing a concurrency conflict. Swing is not thread-safe. I could have spent eternity trying to puzzle this one out if I had not unearthed the Swing-no-thread-safe-kimosabe clue in some obscure post to a forum somewhere. Of course everybody knows Swing is not thread-safe, but it is all too easy to forget that and when there is no exception you have no way to make the connection.
This kind of experience makes me wonder why use threads at all. Back in the VB days I wrote a TCP comm package (because VB had none) and used only a single thread to manage all the sockets and it worked much better than a threaded system, so why even bother with threads? I guess the reason I used them originally is that the retards who wrote the original Java IO API only implemented blocking sockets so unless I wanted the whole interface to hang every time it did a data access there was no choice but to use threads.
With the NIO it is now possible to avoid creating threads altogether. You can use Swing timers to trigger polling on any lazy sockets on the event dispatch thread. This is low overhead and completely avoids any chance of deadlock or concurrency conflict. So the question comes up again, why use threads? Well, I guess if you have two CPUs in the machine and the only way to use both of them is by multi-threading, that might be a reason. If you are too dumb to know how to set up a timered polling system in a maintainable way that might another. I'm starting to run out of reasons. I think I might stop using threads.
|Developer Diary · email@example.com · bio · Revised 7 December 2003 · Pure Content|