In multithreaded code, it is common to use a single main thread that drives the actions that other threads are responsible for. This main thread sends messages, usually by putting them in a queue, and then the other threads process the messages. However, if the main thread throws an exception, the remaining threads will continue to run, waiting for more input to the queue, causing the program to freeze. In this part of diagnosing Java code, a full-time Java developer and a part-time exterminator Eric Allen discusses detecting, fixing, and avoiding this pattern of errors.
Writing code with multithreading is good for programmers. Multithreading makes programming (and programs) much faster, and code can use resources more efficiently. However, as with many things in life, multithreading also has its drawbacks. Because multithreaded code is inherently non-deterministic, there is much greater likelihood of errors. Moreover, the errors that do occur are difficult to reproduce and are therefore more difficult to solve.
Solitary threading Mode
The Java programming language provides rich support for multithreaded code, including a particularly useful feature: the ability to throw an exception in one thread without affecting other threads. But this feature can lead to many bugs that are difficult to track.
It makes sense to recover from a thread's crash, in which case the ability to increase the robustness level of the program. However, it also makes it difficult for us to judge when one of these threads throws an exception. Because the remaining threads will continue to run, the program will show no response or a symptom of freezing the program. This is especially true for programs that frequently communicate between threads.
Consider the example shown in Listing 1, where a pair of threads communicate through the producer-consumer model.
Listing 1. A simple, multi-threaded consumer-producer Program
public class Server extends Thread {
Client client;
int counter;
Public Server (Client _client) {
This.client = _client;
This.counter = 0;
}
public void Run () {
while (counter <) {
This.client.queue.addElement (new Integer (count ER));
counter++;
}
throw new RuntimeException ("Counter >=");
public static void Main (string[] args) {
Client c = new client ();
Server s = new server (c);
C.start ();
S.start ();
}
}
Class Client extends Thread {
Vector queue;
Public Client () {
This.queue = new Vector ();
public void Run () {
while (true) {
if (! (queue.size () = 0)) {
Processnextelement ();
}
}
}
private void Processnextelement () {
Object next = queue.elementat (0);
Queue.removeelementat (0);
System.out.println (next);
}
}