@Override
 public void run() {
   while (goOn) {
     try {
       long[] ids = ManagementFactory.getThreadMXBean().findDeadlockedThreads();
       checkCount.incrementAndGet();
       ids = ids == null ? new long[0] : ids;
       if (ids.length > 0) {
         deadlocked.addAll(asList(ids));
       }
       if (ids.length == 1) {
         throw new RuntimeException("Found 1 deadlocked thread: " + ids[0]);
       } else if (ids.length > 0) {
         ThreadInfo[] infos =
             ManagementFactory.getThreadMXBean().getThreadInfo(ids, Integer.MAX_VALUE);
         System.err.println("Found " + ids.length + " deadlocked threads: ");
         for (ThreadInfo inf : infos) {
           System.err.println(inf.toString());
         }
         throw new RuntimeException("Found " + ids.length + " deadlocked threads");
       }
       Thread.sleep(100);
     } catch (InterruptedException | RuntimeException x) {
       fail(x);
     }
   }
 }
  /**
   * Update the information about completed thread that ran for runtime in milliseconds
   *
   * <p>This method updates all of the key timing and tracking information in the factory so that
   * thread can be retired. After this call the factory shouldn't have a pointer to the thread any
   * longer
   *
   * @param thread the thread whose information we are updating
   */
  @Ensures({"getTotalTime() >= old(getTotalTime())"})
  public synchronized void threadIsDone(final Thread thread) {
    nThreadsAnalyzed++;

    if (DEBUG) logger.warn("UpdateThreadInfo called");

    final long threadID = thread.getId();
    final ThreadInfo info = bean.getThreadInfo(thread.getId());
    final long totalTimeNano = bean.getThreadCpuTime(threadID);
    final long userTimeNano = bean.getThreadUserTime(threadID);
    final long systemTimeNano = totalTimeNano - userTimeNano;
    final long userTimeInMilliseconds = nanoToMilli(userTimeNano);
    final long systemTimeInMilliseconds = nanoToMilli(systemTimeNano);

    if (info != null) {
      if (DEBUG)
        logger.warn(
            "Updating thread with user runtime "
                + userTimeInMilliseconds
                + " and system runtime "
                + systemTimeInMilliseconds
                + " of which blocked "
                + info.getBlockedTime()
                + " and waiting "
                + info.getWaitedTime());
      incTimes(State.BLOCKING, info.getBlockedTime());
      incTimes(State.WAITING, info.getWaitedTime());
      incTimes(State.USER_CPU, userTimeInMilliseconds);
      incTimes(State.WAITING_FOR_IO, systemTimeInMilliseconds);
    }
  }
Пример #3
0
 @RequestMapping("/dumpThead")
 @ResponseBody
 public void doDumpThread(HttpServletRequest request, HttpServletResponse response) {
   try {
     String app = request.getParameter("app");
     String threadId = request.getParameter("threadId");
     ThreadMXBean tBean = JMConnManager.getThreadMBean(app);
     JSONObject data = new JSONObject();
     if (threadId != null) {
       Long id = Long.valueOf(threadId);
       ThreadInfo threadInfo = tBean.getThreadInfo(id, Integer.MAX_VALUE);
       data.put("info", threadInfo.toString());
     } else {
       ThreadInfo[] dumpAllThreads = tBean.dumpAllThreads(false, false);
       StringBuffer info = new StringBuffer();
       for (ThreadInfo threadInfo : dumpAllThreads) {
         info.append("\n").append(threadInfo);
       }
       data.put("info", info);
     }
     writeFile(request, response, data);
   } catch (IOException e) {
     throw new RuntimeException(e);
   }
 }
Пример #4
0
 public Map<String, String> call() {
   Map<String, String> r = new LinkedHashMap<String, String>();
   ThreadInfo[] data = Functions.getThreadInfos();
   Functions.ThreadGroupMap map = Functions.sortThreadsAndGetGroupMap(data);
   for (ThreadInfo ti : data) r.put(ti.getThreadName(), Functions.dumpThreadInfo(ti, map));
   return r;
 }
Пример #5
0
 private void doThreadUpdates() {
   ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
   long threadIds[] = threadMXBean.getAllThreadIds();
   ThreadInfo[] threadInfos = threadMXBean.getThreadInfo(threadIds, 0);
   int threadsNew = 0;
   int threadsRunnable = 0;
   int threadsBlocked = 0;
   int threadsWaiting = 0;
   int threadsTimedWaiting = 0;
   int threadsTerminated = 0;
   for (ThreadInfo threadInfo : threadInfos) {
     // threadInfo is null if the thread is not alive or doesn't exist
     if (threadInfo == null) continue;
     Thread.State state = threadInfo.getThreadState();
     if (state == NEW) {
       threadsNew++;
     } else if (state == RUNNABLE) {
       threadsRunnable++;
     } else if (state == BLOCKED) {
       threadsBlocked++;
     } else if (state == WAITING) {
       threadsWaiting++;
     } else if (state == TIMED_WAITING) {
       threadsTimedWaiting++;
     } else if (state == TERMINATED) {
       threadsTerminated++;
     }
   }
   metrics.setMetric("threadsNew", threadsNew);
   metrics.setMetric("threadsRunnable", threadsRunnable);
   metrics.setMetric("threadsBlocked", threadsBlocked);
   metrics.setMetric("threadsWaiting", threadsWaiting);
   metrics.setMetric("threadsTimedWaiting", threadsTimedWaiting);
   metrics.setMetric("threadsTerminated", threadsTerminated);
 }
Пример #6
0
 MyThreadInfo(long cpuTime, ThreadInfo info) {
   blockedCount = info.getBlockedCount();
   blockedTime = info.getBlockedTime();
   waitedCount = info.getWaitedCount();
   waitedTime = info.getWaitedTime();
   this.cpuTime = cpuTime;
   this.info = info;
 }
Пример #7
0
  public static void main(String[] args) {
    // 获取Java线程管理MXBean
    ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();

    ThreadInfo[] threadInfos = threadMXBean.dumpAllThreads(false, false);
    for (ThreadInfo threadInfo : threadInfos) {
      System.out.println("[" + threadInfo.getThreadId() + " ] " + threadInfo.getThreadName());
    }
  }
Пример #8
0
 void setDelta(long cpuTime, ThreadInfo info) {
   if (deltaDone) throw new IllegalStateException("setDelta already called once");
   blockedCount = info.getBlockedCount() - blockedCount;
   blockedTime = info.getBlockedTime() - blockedTime;
   waitedCount = info.getWaitedCount() - waitedCount;
   waitedTime = info.getWaitedTime() - waitedTime;
   this.cpuTime = cpuTime - this.cpuTime;
   deltaDone = true;
   this.info = info;
 }
Пример #9
0
 /**
  * {@inheritDoc}
  *
  * @see com.wily.introscope.agent.trace.ITracer#ITracer_startTrace(int,
  *     com.wily.introscope.agent.trace.InvocationData)
  */
 @Override
 public void ITracer_startTrace(int tracerIndex, InvocationData data) {
   final int currentIndex = reentrancyIndex.get().incrementAndGet();
   final ThreadInfo ti = TMX.getThreadInfo(Thread.currentThread().getId());
   waitCountBaselines.get().put(currentIndex, ti.getWaitedCount());
   blockCountBaselines.get().put(currentIndex, ti.getBlockedCount());
   if (timesEnabled) {
     waitTimeBaselines.get().put(currentIndex, ti.getWaitedTime());
     blockTimeBaselines.get().put(currentIndex, ti.getBlockedTime());
   }
 }
Пример #10
0
  public static void main(String[] argv) throws Exception {
    mbean = newPlatformMXBeanProxy(server, THREAD_MXBEAN_NAME, ThreadMXBean.class);

    if (!mbean.isSynchronizerUsageSupported()) {
      System.out.println("Monitoring of synchronizer usage not supported");
      return;
    }

    thread.setDaemon(true);
    thread.start();

    // wait until myThread acquires mutex and lock owner is set.
    while (!(mutex.isLocked() && mutex.getLockOwner() == thread)) {
      try {
        Thread.sleep(100);
      } catch (InterruptedException e) {
        throw new RuntimeException(e);
      }
    }

    long[] ids = new long[] {thread.getId()};

    // validate the local access
    ThreadInfo[] infos = getThreadMXBean().getThreadInfo(ids, true, true);
    if (infos.length != 1) {
      throw new RuntimeException(
          "Returned ThreadInfo[] of length=" + infos.length + ". Expected to be 1.");
    }
    thread.checkThreadInfo(infos[0]);

    // validate the remote access
    infos = mbean.getThreadInfo(ids, true, true);
    if (infos.length != 1) {
      throw new RuntimeException(
          "Returned ThreadInfo[] of length=" + infos.length + ". Expected to be 1.");
    }
    thread.checkThreadInfo(infos[0]);

    boolean found = false;
    infos = mbean.dumpAllThreads(true, true);
    for (ThreadInfo ti : infos) {
      if (ti.getThreadId() == thread.getId()) {
        thread.checkThreadInfo(ti);
        found = true;
      }
    }

    if (!found) {
      throw new RuntimeException("No ThreadInfo found for MyThread");
    }

    System.out.println("Test passed");
  }
Пример #11
0
 private int similarity(ThreadInfo threadInfo, ThreadInfo threadInfo0) {
   StackTraceElement[] s1 = threadInfo == null ? EMPTY : threadInfo.getStackTrace();
   StackTraceElement[] s2 = threadInfo0 == null ? EMPTY : threadInfo0.getStackTrace();
   int i = s1.length - 1;
   int j = s2.length - 1;
   int rslt = 0;
   while (i >= 0 && j >= 0 && s1[i].equals(s2[j])) {
     rslt++;
     i--;
     j--;
   }
   return rslt;
 }
Пример #12
0
  public static CharSequence getThreadStats(
      boolean lockedMonitors, boolean lockedSynchronizers, boolean stackTrace) {
    StringBuilder list = new StringBuilder();

    int threadCount = threadMXbean.getThreadCount();
    int daemonCount = threadMXbean.getThreadCount();
    int nonDaemonCount = threadCount - daemonCount;
    int peakCount = threadMXbean.getPeakThreadCount();
    long totalCount = threadMXbean.getTotalStartedThreadCount();

    list.append("Live: .................... ").append(threadCount).append(" threads").append("\n");
    list.append("     Non-Daemon: ......... ")
        .append(nonDaemonCount)
        .append(" threads")
        .append("\n");
    list.append("     Daemon: ............. ").append(daemonCount).append(" threads").append("\n");
    list.append("Peak: .................... ").append(peakCount).append(" threads").append("\n");
    list.append("Total started: ........... ").append(totalCount).append(" threads").append("\n");
    list.append("=================================================").append("\n");

    for (ThreadInfo info : threadMXbean.dumpAllThreads(lockedMonitors, lockedSynchronizers)) {
      list.append("Thread #")
          .append(info.getThreadId())
          .append(" (")
          .append(info.getThreadName())
          .append(")")
          .append("\n");
      list.append("=================================================\n");
      list.append("\tgetThreadState: ...... ").append(info.getThreadState()).append("\n");
      list.append("\tgetWaitedTime: ....... ").append(info.getWaitedTime()).append("\n");
      list.append("\tgetBlockedTime: ...... ").append(info.getBlockedTime()).append("\n");
      for (MonitorInfo monitorInfo : info.getLockedMonitors()) {
        list.append("\tLocked monitor: ....... ").append(monitorInfo).append("\n");
        list.append("\t\t[")
            .append(monitorInfo.getLockedStackDepth())
            .append(".]: at ")
            .append(monitorInfo.getLockedStackFrame())
            .append("\n");
      }

      for (LockInfo lockInfo : info.getLockedSynchronizers()) {
        list.append("\tLocked synchronizer: ...").append(lockInfo).append("\n");
      }
      if (stackTrace) {
        list.append("\tgetStackTace: ..........\n");
        for (StackTraceElement trace : info.getStackTrace())
          list.append("\t\tat ").append(trace).append("\n");
      }
      list.append("=================================================\n");
    }

    return list;
  }
Пример #13
0
  /** Count the number of threads that have a stack frame containing the given string */
  private static int countThreads(String search) {
    ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();

    int count = 0;
    ThreadInfo[] infos = threadBean.getThreadInfo(threadBean.getAllThreadIds(), 20);
    for (ThreadInfo info : infos) {
      if (info == null) continue;
      for (StackTraceElement elem : info.getStackTrace()) {
        if (elem.getClassName().contains(search)) {
          count++;
          break;
        }
      }
    }
    return count;
  }
Пример #14
0
 private String threadDumpDescription() {
   StringBuilder threadDumpDescription = new StringBuilder();
   ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
   ThreadInfo[] threadInfos = threadMXBean.dumpAllThreads(true, true);
   for (ThreadInfo threadInfo : threadInfos) {
     threadDumpDescription.append(
         format(
             "\"%s\"%n\tjava.lang.Thread.State: %s",
             threadInfo.getThreadName(), threadInfo.getThreadState()));
     for (StackTraceElement stackTraceElement : threadInfo.getStackTrace()) {
       threadDumpDescription.append(LINE_SEPARATOR + "\t\tat " + stackTraceElement);
     }
     threadDumpDescription.append(LINE_SEPARATOR + LINE_SEPARATOR);
   }
   return threadDumpDescription.toString();
 }
Пример #15
0
 /**
  * A total hack to see if there are any active Java3D threads running
  *
  * @return any java3d threads running
  */
 private static boolean anyJava3dThreadsActive() {
   ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
   long[] ids = threadBean.getAllThreadIds();
   for (int i = 0; i < ids.length; i++) {
     ThreadInfo info = threadBean.getThreadInfo(ids[i], Integer.MAX_VALUE);
     if (info == null) {
       continue;
     }
     if (info.getThreadState() != Thread.State.RUNNABLE) {
       continue;
     }
     if (info.getThreadName().indexOf("J3D") >= 0) {
       return true;
     }
   }
   return false;
 }
 private Thread findMatchingThread(ThreadInfo inf) {
   for (Thread thread : Thread.getAllStackTraces().keySet()) {
     if (thread.getId() == inf.getThreadId()) {
       return thread;
     }
   }
   throw new IllegalStateException("Deadlocked Thread not found");
 }
Пример #17
0
 /**
  * {@inheritDoc}
  *
  * @see com.wily.introscope.agent.trace.ITracer#ITracer_finishTrace(int,
  *     com.wily.introscope.agent.trace.InvocationData)
  */
 @Override
 public void ITracer_finishTrace(int tracerIndex, InvocationData data) {
   final int currentIndex = reentrancyIndex.get().decrementAndGet();
   try {
     final int priorIndex = currentIndex + 1;
     final ThreadInfo ti = TMX.getThreadInfo(Thread.currentThread().getId());
     long newWaitCount = ti.getWaitedCount();
     long newBlockCount = ti.getBlockedCount();
     long priorWaitCount = waitCountBaselines.get().remove(priorIndex);
     long priorBlockCount = blockCountBaselines.get().remove(priorIndex);
     if (priorWaitCount != NO_ENTRY && !waitCountAcc.IDataAccumulator_isShutOff()) {
       waitCountAcc.ILongAggregatingDataAccumulator_recordDataPoint(newWaitCount - priorWaitCount);
     }
     if (priorBlockCount != NO_ENTRY && !blockCountAcc.IDataAccumulator_isShutOff()) {
       blockCountAcc.ILongAggregatingDataAccumulator_recordDataPoint(
           newBlockCount - priorBlockCount);
     }
     if (timesEnabled) {
       long newWaitTime = ti.getWaitedTime();
       long newBlockTime = ti.getBlockedTime();
       long priorWaitTime = waitTimeBaselines.get().remove(priorIndex);
       long priorBlockTime = blockTimeBaselines.get().remove(priorIndex);
       if (priorWaitTime != NO_ENTRY && !waitTimeAcc.IDataAccumulator_isShutOff()) {
         waitTimeAcc.ILongAggregatingDataAccumulator_recordDataPoint(newWaitTime - priorWaitTime);
       }
       if (priorBlockTime != NO_ENTRY && !blockTimeAcc.IDataAccumulator_isShutOff()) {
         blockTimeAcc.ILongAggregatingDataAccumulator_recordDataPoint(
             newBlockTime - priorBlockTime);
       }
     }
   } finally {
     if (currentIndex < 1) {
       waitCountBaselines.remove();
       blockCountBaselines.remove();
       if (timesEnabled) {
         waitTimeBaselines.remove();
         blockTimeBaselines.remove();
       }
     }
     if (currentIndex < 0) {
       log.warn("Reentrancy Index Underrun:", currentIndex);
       reentrancyIndex.get().set(0);
     }
   }
 }
Пример #18
0
    @DwrPermission(admin = true)
    public ProcessResult getThreadInfo() {
      synchronized (threadInfos) {
        ProcessResult result = new ProcessResult();

        // All of the last thread ids. Ids are removed from this set as they are processed. If ids
        // remain,
        // it means the thread is gone and should be removed from the map.
        Set<Long> threadIds = new HashSet<>(threadInfos.keySet());

        ThreadInfo[] threads = tmxb.getThreadInfo(tmxb.getAllThreadIds(), Integer.MAX_VALUE);
        List<ThreadInfoBean> beans = new ArrayList<>();
        for (ThreadInfo thread : threads) {
          if (thread == null) continue;

          ThreadInfoBean bean = threadInfos.get(thread.getThreadId());
          if (bean == null) {
            bean = new ThreadInfoBean();
            bean.setId(thread.getThreadId());
            bean.setName(thread.getThreadName());
            threadInfos.put(bean.getId(), bean);
          } else threadIds.remove(bean.getId());

          bean.setCpuTime(tmxb.getThreadCpuTime(bean.getId()));
          bean.setState(thread.getThreadState().name());

          if (thread.getThreadState() == State.BLOCKED)
            bean.setState(
                bean.getState()
                    + " by '"
                    + thread.getLockOwnerName()
                    + "' ("
                    + thread.getLockOwnerId()
                    + ")");

          bean.setStackTrace(thread.getStackTrace());

          beans.add(bean);
        }

        // Remove unreferenced threads
        for (Long id : threadIds) threadInfos.remove(id);

        result.addData("threads", beans);

        return result;
      }
    }
Пример #19
0
  /**
   * Java6 を利用した場合にスレッドダンプを取得します。<br>
   *
   * @param info {@link ThreadInfo}オブジェクト
   * @param elements {@link StackTraceElement}オブジェクトの配列
   * @return
   */
  private static String getThreadDumpJava6(ThreadInfo info, StackTraceElement[] elements) {
    StringBuilder sb = getThreadInfoBuffer(info);
    sb.append(NEW_LINE);
    try {
      for (int i = 0; i < elements.length; i++) {
        StackTraceElement ste = elements[i];
        sb.append("\tat " + ste.toString());
        sb.append(NEW_LINE);
        if (i == 0 && getLockInfoMethod__.invoke(info) != null) {
          Thread.State ts = info.getThreadState();
          switch (ts) {
            case BLOCKED:
              sb.append("\t-  blocked on " + getLockInfoMethod__.invoke(info));
              sb.append(NEW_LINE);
              break;
            case WAITING:
              sb.append("\t-  waiting on " + getLockInfoMethod__.invoke(info));
              sb.append(NEW_LINE);
              break;
            case TIMED_WAITING:
              sb.append("\t-  waiting on " + getLockInfoMethod__.invoke(info));
              sb.append(NEW_LINE);
              break;
            default:
          }
        }

        Object[] lockedMonitors = (Object[]) getLockedMonitorsMethod__.invoke(info);

        for (Object mi : lockedMonitors) {
          Integer num = (Integer) getLockedStackDepthMethod__.invoke(mi);
          if (num.intValue() == i) {
            sb.append("\t-  locked " + mi);
            sb.append(NEW_LINE);
          }
        }
      }
      Object[] locks = (Object[]) getLockedSynchronizersMethod__.invoke(info);
      if (locks.length > 0) {
        sb.append(NEW_LINE);
        sb.append("\tNumber of locked synchronizers = " + locks.length);
        sb.append(NEW_LINE);
        for (Object li : locks) {
          sb.append("\t- " + li);
          sb.append(NEW_LINE);
        }
      }
    } catch (InvocationTargetException ex) {
      SystemLogger.getInstance().warn(ex);
    } catch (IllegalAccessException ex) {
      SystemLogger.getInstance().warn(ex);
    }
    sb.append(NEW_LINE);
    return sb.toString();
  }
Пример #20
0
  @RequestMapping("/loadThreadInfo")
  @ResponseBody
  public JSONObject doLoadThreadInfo(HttpServletRequest request) {
    try {
      String app = request.getParameter("app");
      ThreadMXBean tBean = JMConnManager.getThreadMBean(app);
      ThreadInfo[] allThreads = tBean.dumpAllThreads(false, false);

      JSONObject root = new JSONObject();
      JSONArray detail = new JSONArray();
      HashMap<State, Integer> state = new HashMap<Thread.State, Integer>();
      for (ThreadInfo info : allThreads) {
        JSONObject th = new JSONObject();
        long threadId = info.getThreadId();
        long cpu = tBean.getThreadCpuTime(threadId);
        State tState = info.getThreadState();

        th.put("id", threadId);
        th.put("state", tState);
        th.put("name", info.getThreadName());
        th.put("cpu", TimeUnit.NANOSECONDS.toMillis(cpu));
        detail.add(th);

        Integer vl = state.get(tState);
        if (vl == null) {
          state.put(tState, 0);
        } else {
          state.put(tState, vl + 1);
        }
      }

      root.put("state", state);
      root.put("detail", detail);
      root.put("total", tBean.getThreadCount());
      root.put("time", System.currentTimeMillis());
      root.put("deamon", tBean.getDaemonThreadCount());

      return root;
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
Пример #21
0
 private static void printThreadInfo(ThreadInfo threadInfo, StringBuilder threadDump) {
   // Print thread information
   printThread(threadInfo, threadDump);
   // print stack trace with locks
   StackTraceElement[] stacktrace = threadInfo.getStackTrace();
   MonitorInfo[] monitors = threadInfo.getLockedMonitors();
   for (int i = 0; i < stacktrace.length; i++) {
     StackTraceElement ste = stacktrace[i];
     threadDump.append(INDENT + "at " + ste.toString());
     threadDump.append("\n");
     for (int j = 1; j < monitors.length; j++) {
       MonitorInfo mi = monitors[j];
       if (mi.getLockedStackDepth() == i) {
         threadDump.append(INDENT + "  - locked " + mi);
         threadDump.append("\n");
       }
     }
   }
   threadDump.append("\n");
 }
  /**
   * Collect all of the dependencies that exist between threads in this VM, using java management
   * beans and the {@link DependencyMonitor}.
   *
   * <p>Threads may depend on locks, or on other resources that are tracked by the {@link
   * DependencyMonitor}.
   *
   * @arg locality a name tag to stick on entities to help associate them with this JVM and
   *     distinguish them from entities from other jvms
   * @return All of the dependencies between threads and locks or other resources on this VM.
   */
  public static Set<Dependency> collectAllDependencies(Serializable locality) {
    ThreadMXBean bean = ManagementFactory.getThreadMXBean();
    ThreadInfo[] infos = bean.dumpAllThreads(true, true);

    Set<Dependency> results = new HashSet<Dependency>();

    Map<Long, ThreadInfo> threadInfos = new HashMap<Long, ThreadInfo>();
    for (ThreadInfo info : infos) {
      // This can happen if the thread died.
      if (info == null) {
        continue;
      }

      for (LockInfo monitor : info.getLockedMonitors()) {
        Dependency dependency =
            new Dependency(new LocalLockInfo(locality, monitor), new LocalThread(locality, info));
        results.add(dependency);
      }

      for (LockInfo sync : info.getLockedSynchronizers()) {
        Dependency dependency =
            new Dependency(new LocalLockInfo(locality, sync), new LocalThread(locality, info));
        results.add(dependency);
      }

      LockInfo waitingFor = info.getLockInfo();
      if (waitingFor != null) {
        Dependency dependency =
            new Dependency(
                new LocalThread(locality, info), new LocalLockInfo(locality, waitingFor));
        results.add(dependency);
      }

      threadInfos.put(info.getThreadId(), info);
    }

    Set<Dependency> monitoredDependencies =
        collectFromDependencyMonitor(bean, locality, threadInfos);
    results.addAll(monitoredDependencies);
    return results;
  }
Пример #23
0
  public static void main(String[] args) throws Exception {
    // TODO Auto-generated method stub
    if (args.length != 4) {
      System.err.println("Please provide process id zabbix-host zabbix-port host-guid");
      System.exit(-1);
    }
    String processPid = args[0];
    String zabbixHost = args[1];
    String zabbixPort = args[2];
    String hostGuid = args[3];

    VirtualMachine vm = VirtualMachine.attach(processPid);
    String connectorAddr =
        vm.getAgentProperties().getProperty("com.sun.management.jmxremote.localConnectorAddress");
    if (connectorAddr == null) {
      String agent =
          vm.getSystemProperties().getProperty("java.home")
              + File.separator
              + "lib"
              + File.separator
              + "management-agent.jar";
      vm.loadAgent(agent);
      connectorAddr =
          vm.getAgentProperties().getProperty("com.sun.management.jmxremote.localConnectorAddress");
    }
    JMXServiceURL serviceURL = new JMXServiceURL(connectorAddr);
    JMXConnector connector = JMXConnectorFactory.connect(serviceURL);
    MBeanServerConnection mbsc = connector.getMBeanServerConnection();
    ObjectName objName = new ObjectName(ManagementFactory.THREAD_MXBEAN_NAME);
    Set<ObjectName> mbeans = mbsc.queryNames(objName, null);
    for (ObjectName name : mbeans) {
      ThreadMXBean threadBean;
      threadBean =
          ManagementFactory.newPlatformMXBeanProxy(mbsc, name.toString(), ThreadMXBean.class);
      long threadIds[] = threadBean.getAllThreadIds();
      for (long threadId : threadIds) {
        ThreadInfo threadInfo = threadBean.getThreadInfo(threadId);
        System.out.println(threadInfo.getThreadName() + " / " + threadInfo.getThreadState());
      }
    }
  }
Пример #24
0
  /**
   * Return current (raw) list of thread info objects wrapped in ThreadRankInfo type.
   *
   * @return list of threads
   */
  protected List<ThreadRankInfo> rawList() {
    // Platform MBean Server startup might be suspended (eg. for JBoss AS);
    if (threadMXBean == null) {
      if (mBeanServerRegistry.lookup("java") != null) {
        threadMXBean = ManagementFactory.getThreadMXBean();
      } else {
        return new ArrayList<ThreadRankInfo>(1);
      }
    }

    ThreadInfo[] ati = threadMXBean.getThreadInfo(threadMXBean.getAllThreadIds());
    List<ThreadRankInfo> lst = new ArrayList<ThreadRankInfo>(ati.length);

    for (ThreadInfo ti : ati) {
      long tid = ti.getThreadId();
      long cpuTime = threadMXBean.getThreadCpuTime(tid);
      lst.add(new ThreadRankInfo(tid, ti.getThreadName(), cpuTime, ti.getBlockedTime()));
    }

    return lst;
  }
Пример #25
0
 public static String threadDump() {
   final StringBuilder dump = new StringBuilder();
   final java.lang.management.ThreadMXBean threadMXBean =
       java.lang.management.ManagementFactory.getThreadMXBean();
   final java.lang.management.ThreadInfo[] threadInfos =
       threadMXBean.getThreadInfo(threadMXBean.getAllThreadIds(), 100);
   for (java.lang.management.ThreadInfo threadInfo : threadInfos) {
     dump.append('"');
     dump.append(threadInfo.getThreadName());
     dump.append("\" ");
     final Thread.State state = threadInfo.getThreadState();
     dump.append("\n   java.lang.Thread.State: ");
     dump.append(state);
     final StackTraceElement[] stackTraceElements = threadInfo.getStackTrace();
     for (final StackTraceElement stackTraceElement : stackTraceElements) {
       dump.append("\n        at ");
       dump.append(stackTraceElement);
     }
     dump.append("\n\n");
   }
   return dump.toString();
 }
Пример #26
0
  private static void dumpThreadInfo(
      StringBuilder threadDump, boolean withLocks, ThreadMXBean threadMx) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String timestamp = dateFormat.format(new Date());
    threadDump.append(timestamp);
    threadDump.append("\nFull thread dump ");
    threadDump.append("\n");

    if (withLocks) {
      ThreadInfo[] threadInfos = threadMx.dumpAllThreads(true, true);
      for (ThreadInfo threadInfo : threadInfos) {
        printThreadInfo(threadInfo, threadDump);
        LockInfo[] syncs = threadInfo.getLockedSynchronizers();
        printLockInfo(syncs, threadDump);
      }
      threadDump.append("\n");
    } else {
      long[] threadIds = threadMx.getAllThreadIds();
      ThreadInfo[] threadInfos = threadMx.getThreadInfo(threadIds, Integer.MAX_VALUE);
      for (ThreadInfo threadInfo : threadInfos) printThreadInfo(threadInfo, threadDump);
    }
  }
Пример #27
0
  /**
   * Fullスレッドダンプを取得します。<br>
   *
   * @return Fullスレッドダンプ
   */
  public static String getFullThreadDump() {
    StringBuilder builder = new StringBuilder(DEF_BUILDER_SIZE);

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    // 時刻を出力する。
    long now = System.currentTimeMillis();
    builder.append(NEW_LINE);
    builder.append(format.format(now));
    builder.append(NEW_LINE);

    // ヘッダ部を出力する。
    builder.append(THREAD_DUMP_HEAD_START);
    builder.append(System.getProperty("java.vm.name"));
    builder.append(" (");
    builder.append(System.getProperty("java.version"));
    builder.append(THREAD_DUMP_HEAD_END);
    builder.append(NEW_LINE);

    // 各スレッドの情報を取得する。
    long[] threadIds = getAllThreadIds();
    ThreadInfo[] threadInfos = getThreadInfo(threadIds, Integer.MAX_VALUE);
    for (ThreadInfo threadInfo : threadInfos) {
      StackTraceElement[] elements = threadInfo.getStackTrace();
      String threadDump = null;
      if (getLockedSynchronizersMethod__ != null
          && getLockedMonitorsMethod__ != null
          && getLockInfoMethod__ != null
          && getLockedStackDepthMethod__ != null) {
        threadDump = getThreadDumpJava6(threadInfo, elements);
      } else {
        threadDump = getThreadDumpJava5(threadInfo, elements);
      }
      builder.append(threadDump);
    }

    return builder.toString();
  }
Пример #28
0
  @Override
  public void run() {

    boolean dead = false;
    while (!dead && !interrupted()) {
      try {
        Thread.sleep(10000);
      } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        dead = true;
      }
      ThreadMXBean tmx = ManagementFactory.getThreadMXBean();
      long[] ids = tmx.findDeadlockedThreads();
      if (ids != null) {
        Spout.getLogger().info("Checking for deadlocks");
        ThreadInfo[] infos = tmx.getThreadInfo(ids, true, true);
        Spout.getLogger().severe("The following threads are deadlocked:");
        for (ThreadInfo ti : infos) {
          Spout.getLogger().severe(ti.toString());
        }
      }
    }
  }
Пример #29
0
 /**
  * スレッドの状態をStringBufferにして返します。<br>
  *
  * @param info {@link ThreadInfo}オブジェクト
  * @return スレッドの状態をStringBufferにして返したもの。
  */
 private static StringBuilder getThreadInfoBuffer(ThreadInfo info) {
   StringBuilder sb =
       new StringBuilder(
           "\""
               + info.getThreadName()
               + "\""
               + " Id="
               + info.getThreadId()
               + " "
               + info.getThreadState());
   if (info.getLockName() != null) {
     sb.append(" on " + info.getLockName());
   }
   if (info.getLockOwnerName() != null) {
     sb.append(" owned by \"" + info.getLockOwnerName() + "\" Id=" + info.getLockOwnerId());
   }
   if (info.isSuspended()) {
     sb.append(" (suspended)");
   }
   if (info.isInNative()) {
     sb.append(" (in native)");
   }
   return sb;
 }
Пример #30
0
  private static boolean isIdleThread(ThreadInfo threadInfo) {
    String threadName = threadInfo.getThreadName();

    // NOTE: these are likely JVM dependent
    if (threadName.equals("Signal Dispatcher")
        || threadName.equals("Finalizer")
        || threadName.equals("Reference Handler")) {
      return true;
    }

    for (StackTraceElement frame : threadInfo.getStackTrace()) {
      String className = frame.getClassName();
      String methodName = frame.getMethodName();
      if (className.equals("java.util.concurrent.ThreadPoolExecutor")
          && methodName.equals("getTask")) {
        return true;
      }
      if (className.equals("sun.nio.ch.SelectorImpl") && methodName.equals("select")) {
        return true;
      }
      if (className.equals("org.elasticsearch.threadpool.ThreadPool$EstimatedTimeThread")
          && methodName.equals("run")) {
        return true;
      }
      if (className.equals("org.elasticsearch.indices.ttl.IndicesTTLService$Notifier")
          && methodName.equals("await")) {
        return true;
      }
      if (className.equals("java.util.concurrent.LinkedTransferQueue")
          && methodName.equals("poll")) {
        return true;
      }
    }

    return false;
  }