If you are not careful, the thread may disappear from the server application without a (stack) trace. In this article, the thread expert Brian Goetz provides the technology used to prevent and detect "unauthorized" threads.
When the main thread in a single-threaded application throws an uncaptured exception, you may notice that the stack trace is printed in the console (or because the program is stopped. However, in multi-threaded applications, especially applications that run as servers and are not connected to the console, thread death may become a very noticeable event, which may cause local system failure, this leads to chaotic application behavior.
InJava Theory and PracticeIn the column article of February October, we studied the thread pool and how the incorrectly written thread pool would "leak" the thread until all threads are eventually lost. Most thread pools prevent this by capturing thrown exceptions or restarting dead threads, however, the thread leakage issue is not limited to the thread pool-server applications that use threads to provide services for the work queue may also have this problem. When a worker thread is lost for a server application, the application may still be normal for a long time, which makes the real cause of the problem difficult to determine.
Many applications use threads to provide backend services-to process tasks from the event queue, to read commands from the socket, or to execute long-term tasks other than the UI thread. When an uncapturedRuntimeExceptionOrError, Or just stop and wait for the blocked I/O operation (originally not expected to be blocked), so what will happen when one of these threads dies?
Sometimes, for example, when a thread executes a user-initiated long-term task (such as a spelling check), the user will notice that the task is not progressing and they may terminate the operation or program abnormally. However, at other times, the backend threads run the "cleaning and maintenance" task, which may disappear for a long time without being noticed.
Sample server application
Consider a hypothetical middleware server application that aggregates messages from various input sources and then submits them to an external server application, receive responses from external applications and route the responses back to the appropriate input source. For each input source, there is a plug-in that accepts its input messages in its own way (by scanning the file directory, waiting for socket connection, polling the database table, etc ). Plug-ins can be compiled by third parties, even if they are running on the server JVM. This application has (at least) two internal work queues-messages received from the plug-in waiting for being sent to the server ("outbound message" Queue ), and the response received from the server waiting to be passed to the appropriate plug-in ("inbound response" Queue ). By calling the service routine on the plug-in objectincomingResponse(), The message is routed to the plug-in that originally sent the request.
After receiving messages from the plug-in, messages are arranged in the outbound message queue. One or more threads that read messages from the queue process the messages in the outbound message queue, record their sources, and submit the messages to the remote server application (assuming that they are through the Web Service Interface ). The Remote Application finally returns a response through the Web service interface, and then our server arranges the received response to the inbound response queue. One or more response threads read messages from the inbound response queue and route them to the appropriate plug-in to complete the round-trip ".
In this application, there are two message queues for both outbound requests and inbound responses. Different plug-ins may also have another queue. We also have several service threads, one reading requests from the outbound message queue and submitting them to the external server, one reading the response from the inbound response queue and routing it to the plug-in, some threads may also exist in the plug-ins used to provide services to sockets or other external request sources.
It is not always obvious when the thread fails.
What will happen if one of these threads (such as the response dispatch thread) disappears? Because the plug-ins can still submit new messages, they may not immediately notice some errors. Messages will still arrive through various input sources and be submitted to external services through our applications. Because the plug-in does not expect immediate response, it still does not realize the problem. Finally, the received response will be filled with the queue. If they are stored in the memory, the memory will eventually be used up. Even if the memory is not exhausted, some people may find that the response is not delivered at a certain time point-but this may take some time, because other aspects of the system can still work normally.
When the main task processing is handled by a thread pool rather than a single thread, the consequences of accidental thread leakage are protected to a certain extent, because a thread pool with good execution performance is an eight-thread pool, the efficiency of using seven threads to complete its work may still be acceptable. At first, there may be no significant difference. However, the system performance will eventually decline, although this decline is not easy to detect.
The thread leakage problem in server applications is that it is not always easy to detect from outside. Because most threads only process part of the server's workload, or may only process specific types of background tasks, when the program actually encounters a serious fault, it still works normally in the user's opinion. This, coupled with the cause of thread leakage, does not always leave a clear trace, it will lead to surprising or even confusing application behavior.
Runtimeexception is the primary cause of thread death.
They may disappear when the thread throws uncaptured exceptions or errors, while the I/O operations that the thread waits for will never be completed, or no one calls them for the monitor they are waiting.notify()They only stop working. The most common cause of accidental thread death isRuntimeException(For exampleNullPointerException,ArrayIndexOutOfBoundsException). In our example applicationincomingResponse()When the response is passed back to the plug-in, it may throwRuntimeException. The plug-in code may be written by a third party or after the application is compiled, so the application writer cannot review its correctness. If some plug-ins throwRuntimeExceptionSome response service threads will terminate, which means that an erroneous plug-in will crash the entire system. Unfortunately, this vulnerability is common.
Although the compiler "Hopes" that we will actively compile code for the exceptions that have been detected (the compiler will force us to do so ), however, most Java developers ignore unknown exceptions to a large extent. In a single-threaded application, unprocessedRuntimeExceptionThe results are obvious, and there is a clear stack trace for the location where an exception occurs, which provides the problem notification and useful information for solving the problem. However, in multi-threaded applications, threads will die silently due to unknown exceptions-making users and developers have no clue about the problems and why they occur.
The thread that processes the task (similar to the request and response handler in the example application), basically spends its entire lifecycle passing through a similarRunnableAbstract obstacle to call the service method. Because we do not know what is on the other side of this abstract obstacle, we should doubt whether it is so good as to assume that it never throws an unknown exception. If the service routine throwsRuntimeException, The Calling thread should capture this exception, record it to the log, then switch to the next item in the queue or close the thread, and then restart it. (The last option comes from the assumption that any throwRuntimeExceptionOr the error code may have damaged the thread status .)
The code in Listing 1 is typical from the work queueRunnableThe task thread is similar to the inbound response thread in our example. It is not prepared to throw any plug-ins that do not detect exceptions.
List 1. workthreads that do not guard against runtimeexception
private class TrustingPoolWorker extends Thread { public void run() { IncomingResponse ir; while (true) { ir = (IncomingResponse) queue.getNext(); PlugIn plugIn = findPlugIn(ir.getResponseId()); if (plugIn != null) plugIn.handleMessage(ir.getResponse()); else log("Unknown plug-in for response " + ir.getResponseId()); } }}
|
We do not need to add much code to make this worker thread more robust to handle faults in the plug-in code. As longRuntimeExceptionAnd then perform the rectification operation to ensure that we have the ability to prevent a poorly written plug-in from damaging the entire server. The appropriate Rectification Operation should record the error to the log, then simply go to the next message, terminate the current thread and restart it (this is similarTimerTaskOr uninstall the plug-in that causes the problem, as shown in Listing 2:
List 2. workthreads guard against runtimeexception
private class SaferPoolWorker extends Thread { public void run() { IncomingResponse ir; while (true) { ir = (IncomingResponse) queue.getNext(); PlugIn plugIn = findPlugIn(ir.getResponseId()); if (plugIn != null) { try { plugIn.handleMessage(ir.getResponse()); } catch (RuntimeException e) { // Take some sort of action; // - log the exception and move on // - log the exception and restart the worker thread // - log the exception and unload the offending plug-in } } else log("Unknown plug-in for response " + ir.getResponseId()); } }}
|
Use the uncaptured exception handler provided by threadgroup
Besides viewing external code as more likely to throwRuntimeExceptionIn addition toThreadGroupClassuncaughtExceptionFunctions are also wise.ThreadGroupNot very useful, but currently (until in JDK 1.5ThreadAdded uncaptured Exception Handling ),uncaughtExceptionFeatures are currently indispensable. Listing 3 shows an example usingThreadGroupTo detect the thread death caused by uncaptured exceptions.
Listing 3. Using uncaughtexception to detect thread death
public class ThreadGroupExample { public static class MyThreadGroup extends ThreadGroup { public MyThreadGroup(String s) { super(s); } public void uncaughtException(Thread thread, Throwable throwable) { System.out.println("Thread " + thread.getName() + " died, exception was: "); throwable.printStackTrace(); } } public static ThreadGroup workerThreads = new MyThreadGroup("Worker Threads"); public static class WorkerThread extends Thread { public WorkerThread(String s) { super(workerThreads, s); } public void run() { throw new RuntimeException(); } } public static void main(String[] args) { Thread t = new WorkerThread("Worker Thread"); t.start(); }}
|
If a thread in the thread group dies when an uncaptured exception is thrown,uncaughtException()This method can write a record to the log, restart the thread, restart the system, or take any corrective or diagnostic operations that it deems necessary. At least, if all threads write a log message when the thread dies, you will have a record of when and where errors occur, rather than wondering where your request processing thread went.
Conclusion
When the thread disappears from the application, it will cause confusion. In many cases, when the thread disappears, there is no (stack) trace. Like dealing with many risks, the best way to prevent thread leakage is to combine prevention with detection; note that it is possible to throwRuntimeException(For example, when calling external code), and useThreadGroupProvideduncaughtExceptionHandler to detect abnormal termination of a thread.