Monday, April 7, 2014

How To Kill Tomcat HTTP Stuck Thread

Stuck Thread Problem:

In one of our application we were facing issue of stuck thread,it can not complete current work and also not able to accept new work.

Once thread is stuck,CPU utilization starts increasing slowly, as stucked thread is utilizing more CPU, other threads start performing slowly makes the environment slow for users  and at some point it brings your server down.

Restarting server in business hours is not good for anyone ,and it creates the bad impression of IT department to business.

Identify Stuck Threads:

To identify which are stuck threads ,you can use jconsole and  topthreads plugin.once you identified the top http threads which are consuming more memory you can kill stuck threads using below solution.


Stuck Thread Solution:
so we have implemented below solution for stuck thread which we found on web.

in java you can create jsp with below code and call jsp using URL something like this-
http://servername:port/context/jspname.jsp?threadName=http-8080-6

<%@page language="java"%>
 <%
     String threadNameToKill = request.getParameter("threadName");
     killThread(threadNameToKill, out);
 %>
 <%!
     public void killThread(String threadNameToKill, JspWriter out) throws Exception {
         ThreadGroup root = Thread.currentThread().getThreadGroup().getParent();
         while (root.getParent() != null) {
             root = root.getParent();
         }
         visit(root, 0, threadNameToKill,out);
     }

    public void visit(ThreadGroup group, int level, String threadNameToKill,JspWriter out) throws Exception {
         int numThreads = group.activeCount();
         Thread[] threads = new Thread[numThreads * 2];
         numThreads = group.enumerate(threads, false);
         for (int i = 0; i < numThreads; i++) { // Get thread
             Thread thread = threads[i];
             if (threadNameToKill.equals(thread.getName())) {
         thread.stop();
                 out.write("
Thread " + threadNameToKill + " stopped. It should disappear from threads list in few seconds...");
                 break;
             }
         }
         int numGroups = group.activeGroupCount();
         ThreadGroup[] groups = new ThreadGroup[numGroups * 2];
         numGroups = group.enumerate(groups, false);
         for (int i = 0; i < numGroups; i++) {
             visit(groups[i], level + 1, threadNameToKill, out);
         }
     }
 %>




No comments: