48.

Overview

When your multithread program freezes and stack traces don't print to standard error, there's a chance you've discovered the hard-to-track Orphaned Thread bug pattern. We discuss the obvious fix and detail ways to detect and prevent this bug.

Writing code with multiple threads can make the programming (and the program) go much faster—and the code can use resources much more effectively. However, as with most things in life, there are drawbacks. Because multithreaded code is inherently nondeterministic, the potential for errors is much greater. What's more, the errors that do occur will be much harder to reproduce, and therefore tougher to pin down.

The Java programming language provides abundant support for multithreaded code, including one feature that can be especially useful: the ability to throw an exception in one thread without affecting the others. But this feature can cause many hard-to-track bugs.

Tip 

Multithreaded code is inherently nondeterministic, so it can potentially introduce errors that will be much harder to reproduce and identify.

In cases where it makes sense to recover from a crash in one of the threads, this ability can add a level of robustness to a program. It can, however, make it difficult to determine which thread has thrown an exception. Because the remaining threads will continue to run, the program may exhibit the signs of an unresponsive or frozen program. This is particularly true in a program where the threads communicate with each other often. I call this the Orphaned Thread bug pattern.

Here is this bug pattern in a nutshell:

  • Pattern: Orphaned Thread.

  • Symptoms: A multithreaded program locks up with or without printing stack traces to standard error.

  • Cause: Various program threads are stuck waiting for input from a thread that exited after an uncaught exception was thrown.

  • Cures and Preventions: Put exception-handling code in the main thread to notify the dependent threads of the exceptional condition. Alternatively, put a handler into the thread that exited so that it passes information to its clients instead.



Bug Patterns in Java
Bug Patterns In Java
ISBN: 1590590619
EAN: 2147483647
Year: N/A
Pages: 95
Authors: Eric Allen

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net