List of usage examples for java.lang Thread getId
public long getId()
From source file:com.iorga.webappwatcher.analyzer.model.session.RequestsTimesAndStacks.java
private void computeGroupedStacksForRequest(final RequestEventLog request, final TreeNode<StackStatElement> groupedStacksRoot) { // retrieve all system logs for that request if any final List<SystemEventLog> systems = slowRequestSystemLogs.get(request); // for all that system events, will retrieve the thread of the request for (final SystemEventLog system : systems) { for (final Thread thread : system.getBlockedOrRunningThreads()) { if (thread.getId() == request.getThreadId()) { // This is the thread of the request, let's add the stack to the StackStatElement children final StackTraceElement[] stackTraces = thread.getStackTrace(); recurseAddStackElement(groupedStacksRoot, stackTraces, stackTraces.length); break; // found }//from ww w .j av a 2 s . c o m } } }
From source file:com.dianping.dpsf.jmx.DpsfResponsorMonitor.java
private String getThreadStackTraces(RequestProcessor requestProcessor, State state, int threadCount) { ThreadGroup threadGroup = requestProcessor.getThreadPool().getFactory().getGroup(); Thread[] threads = new Thread[threadGroup.activeCount()]; threadGroup.enumerate(threads, false); StringBuilder builder = new StringBuilder(); int count = 0; if (threads != null && threads.length > 0 && threadCount > 0) { for (Thread thread : threads) { if (state == thread.getState()) { count++;//from ww w . j av a2 s.c o m if (count > 1) { builder.append("\r\n\r\n"); } builder.append("Thread ").append(thread.getId()).append(" ").append(thread.getName()) .append(" (state = ").append(state).append(")").append("\r\n"); StackTraceElement[] stackTrace = thread.getStackTrace(); for (StackTraceElement ste : stackTrace) { builder.append(ste.getClassName()).append("-").append(ste.getMethodName()).append("(") .append(ste.getLineNumber()).append(")").append("\r\n"); } if (count >= threadCount) { break; } } } } return builder.toString(); }
From source file:com.github.nethad.clustermeister.provisioning.jppf.LocalDriverBuilder.java
@Override protected ClustermeisterLauncher doBuild() { JPPFDriverConfigurationSource.serverPort = serverPort; JPPFDriverConfigurationSource.managementPort = managementPort; JPPFDriverConfigurationSource.jvmOptions = configuration .getString(ConfigurationKeys.JVM_OPTIONS_LOCAL_DRIVER, ""); Map<String, String> loadBalancingConfigValues = new DriverLoadBalancing(configuration) .getLoadBalancingConfigValues(); if (loadBalancingConfigValues.isEmpty()) { // logger.info("No load balancing settings set."); } else {// w w w.j a va2 s . c om for (Map.Entry<String, String> entry : loadBalancingConfigValues.entrySet()) { // logger.info("{} => {}", entry.getKey(), entry.getValue()); } } JPPFDriverConfigurationSource.loadBalancing = new DriverLoadBalancing(configuration) .getLoadBalancingConfigValues(); final ClustermeisterLauncher launcher = new ClustermeisterDriverLauncher(true); final AtomicBoolean initialized = new AtomicBoolean(false); final Monitor initializationMonitor = new Monitor(false); final Monitor.Guard isInitialized = new Monitor.Guard(initializationMonitor) { @Override public boolean isSatisfied() { return initialized.get(); } }; launcher.addObserver(new Observer() { @Override public void update(Observable o, Object arg) { initializationMonitor.enter(); try { initialized.set(true); } finally { initializationMonitor.leave(); } } }); Thread driverThread = new Thread(new Runnable() { @Override public void run() { try { launcher.doLaunch(true, ClustermeisterProcessLauncher.StreamSink.LOG); } catch (Throwable ex) { logger.warn("Execption from local driver thread.", ex); } } }); driverThread.setName(String.format("%s-%s", DRIVER_THREAD_NAME, driverThread.getId())); driverThread.start(); //wait for driver to initialize. initializationMonitor.enter(); try { try { initializationMonitor.waitFor(isInitialized); } catch (InterruptedException ex) { logger.warn("Interrupted while waiting for local driver to initialize! " + "Initialization may not be complete.", ex); } } finally { initializationMonitor.leave(); } return launcher; }
From source file:org.commonjava.indy.diag.data.DiagnosticsManager.java
public String getThreadDumpString() { Thread[] threads = new Thread[Thread.activeCount()]; Thread.enumerate(threads);/*from w w w .ja v a2 s . c om*/ Map<Long, Thread> threadMap = new HashMap<>(); Stream.of(threads).forEach(t -> threadMap.put(t.getId(), t)); ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); ThreadInfo[] threadInfos = threadMXBean.getThreadInfo(threadMXBean.getAllThreadIds(), 100); StringBuilder sb = new StringBuilder(); Stream.of(threadInfos).forEachOrdered((ti) -> { if (sb.length() > 0) { sb.append("\n\n"); } String threadGroup = "Unknown"; Thread t = threadMap.get(ti.getThreadId()); if (t != null) { ThreadGroup tg = t.getThreadGroup(); if (tg != null) { threadGroup = tg.getName(); } } sb.append(ti.getThreadName()).append("\n Group: ").append(threadGroup).append("\n State: ") .append(ti.getThreadState()).append("\n Lock Info: ").append(ti.getLockInfo()) .append("\n Monitors:"); MonitorInfo[] monitors = ti.getLockedMonitors(); if (monitors == null || monitors.length < 1) { sb.append(" -NONE-"); } else { sb.append("\n - ").append(join(monitors, "\n - ")); } sb.append("\n Trace:\n ").append(join(ti.getStackTrace(), "\n ")); }); return sb.toString(); }
From source file:com.wavemaker.runtime.server.ServiceResponse.java
private void cleanup() { for (Map.Entry<String, Thread> entry : this.threads.entrySet()) { String requestId = entry.getKey(); Thread thread = entry.getValue(); if (!thread.isAlive()) { Tuple.Two<Long, JSONObject> t = this.serviceResponseTable.get(requestId); if (t != null) { long time = t.v1; if (System.currentTimeMillis() - time > (this.connectionTimeout - 3) * 1000 * 2) { log.debug("ServiceResponse: Cleanup: Remvoving: " + requestId + " " + thread.getId() + " ---"); this.serviceResponseTable.remove(requestId); this.threads.remove(requestId); }//from w w w .jav a2 s .c o m } } } }
From source file:com.iorga.webappwatcher.RequestLogFilter.java
@SuppressWarnings("unchecked") private RequestEventLog createRequestEventLog(final HttpServletRequest httpRequest, final String requestURI) { final RequestEventLog logRequest = EventLogManager.getInstance().addEventLog(RequestEventLog.class); logRequest.setRequestURI(requestURI); logRequest.setMethod(httpRequest.getMethod()); final Enumeration<String> parameterNames = httpRequest.getParameterNames(); final List<Parameter> parameters = new LinkedList<Parameter>(); while (parameterNames.hasMoreElements()) { final String parameterName = parameterNames.nextElement(); parameters.add(new Parameter(parameterName, httpRequest.getParameterValues(parameterName))); }/* w w w . ja v a 2 s . com*/ logRequest.setParameters(parameters.toArray(new Parameter[parameters.size()])); final Enumeration<String> headerNames = httpRequest.getHeaderNames(); final List<Header> headers = new LinkedList<Header>(); while (headerNames.hasMoreElements()) { final String headerName = headerNames.nextElement(); headers.add(new Header(headerName, httpRequest.getHeader(headerName))); } logRequest.setHeaders(headers.toArray(new Header[headers.size()])); final Principal userPrincipal = httpRequest.getUserPrincipal(); if (userPrincipal != null) { logRequest.setPrincipal(userPrincipal.getName()); } final Thread currentThread = Thread.currentThread(); logRequest.setThreadName(currentThread.getName()); logRequest.setThreadId(currentThread.getId()); return logRequest; }
From source file:org.kaaproject.kaa.server.common.thrift.cli.server.BaseCliThriftService.java
/** * Retrieve all threads info from thread group. * * @param group the thread group//from www . j a v a2 s.c om * @param threadsMap the threads map to store threads info */ private void allThreadsFromGroup(ThreadGroup group, Map<Long, ThreadStruct> threadsMap) { int threadCount = group.activeCount(); int groupCount = group.activeGroupCount(); Thread[] groupThreads = new Thread[threadCount]; ThreadGroup[] threadGroups = new ThreadGroup[groupCount]; group.enumerate(groupThreads, false); group.enumerate(threadGroups, false); for (Thread t : groupThreads) { if (t != null) { ThreadStruct ts = threadsMap.get(t.getId()); ts.thread = t; } } for (ThreadGroup tg : threadGroups) { allThreadsFromGroup(tg, threadsMap); } }
From source file:org.openqa.selenium.diags.Stats.java
private void doPerThreadReport(PrintStream out, Map<String, StatEvent> itemMap) { Set<String> items = new TreeSet<String>(itemMap.keySet()); for (Thread threadId : seenThreads.keySet()) { table(out);//from w w w . ja v a 2s .c o m final Long lstSeent = lastSeen.get(threadId); final Long startedAt = startTime.get(threadId); long totalElapsed = lstSeent - startedAt; long clientSideElapsed = totalElapsed; tableHeader(out); for (String key : items) { StatEvent statEvent = itemMap.get(key); clientSideElapsed -= statEvent.getTotalElapsed(threadId.getId()); out.println( "<tr><td>" + trim(key) + "</td>" + statEvent.getAsTableCells(threadId.getId()) + "</tr>"); } out.println("<tr><td colspan='4'><b>====== Thread id + " + threadId + "(" + seenThreads.get(threadId) + ") =====</b></td></tr>"); out.println("<tr><td colspan='4'>Total elapsed " + totalElapsed + "ms, of which " + clientSideElapsed + "ms is within the test fixture itself</td></tr>"); tableFooter(out); } }
From source file:voldemort.tools.DeleteKeysCLI.java
public void deleteKeys() throws Exception { Map<String, Thread> workers = new HashMap<String, Thread>(); Map<String, DeleteKeysTask> tasks = new HashMap<String, DeleteKeysTask>(); BufferedWriter statusWriter = new BufferedWriter(new FileWriter("status.txt", true)); for (String store : this.stores) { DeleteKeysTask task = new DeleteKeysTask(store, storeClients.get(store), this.adminClient, serializerDefs.get(store), this.keyFile, this.qps, this.nodeid, this.deleteAllVersions, this.checkKeysCount); Thread worker = new Thread(task); workers.put(store, worker);//from w w w .jav a2 s . c o m tasks.put(store, task); statusWriter.write("Created thread " + worker.getId() + " for store " + store + "\n"); System.out.println("Created thread " + worker.getId() + " for store " + store); worker.start(); } statusWriter.flush(); boolean isAllCompleted = false; while (isAllCompleted == false) { isAllCompleted = true; for (String store : stores) { Thread worker = workers.get(store); DeleteKeysTask task = tasks.get(store); System.out.print(task.getStatus()); statusWriter.write(task.getStatus()); if (task.isComplete()) { continue; } if (worker.isAlive() == false) { System.out.println("Thread processing it has died " + store); statusWriter.write("Thread processing it has died " + store + "\n"); continue; } isAllCompleted = false; } statusWriter.flush(); if (isAllCompleted == false) { Thread.sleep(1000 * 15); } } statusWriter.close(); }
From source file:com.occamlab.te.web.TestServlet.java
public void processFormData(HttpServletRequest request, HttpServletResponse response) throws ServletException { try {/*from w w w. j a v a2 s .c om*/ FileItemFactory ffactory; ServletFileUpload upload; List /* FileItem */ items = null; HashMap<String, String> params = new HashMap<String, String>(); boolean multipart = ServletFileUpload.isMultipartContent(request); if (multipart) { ffactory = new DiskFileItemFactory(); upload = new ServletFileUpload(ffactory); items = upload.parseRequest(request); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { params.put(item.getFieldName(), item.getString()); } } } else { Enumeration paramNames = request.getParameterNames(); while (paramNames.hasMoreElements()) { String name = (String) paramNames.nextElement(); params.put(name, request.getParameter(name)); } } HttpSession session = request.getSession(); ServletOutputStream out = response.getOutputStream(); String operation = params.get("te-operation"); if (operation.equals("Test")) { TestSession s = new TestSession(); String user = request.getRemoteUser(); File logdir = new File(conf.getUsersDir(), user); String mode = params.get("mode"); RuntimeOptions opts = new RuntimeOptions(); opts.setWorkDir(conf.getWorkDir()); opts.setLogDir(logdir); if (mode.equals("retest")) { opts.setMode(Test.RETEST_MODE); String sessionid = params.get("session"); String test = params.get("test"); if (sessionid == null) { int i = test.indexOf("/"); sessionid = i > 0 ? test.substring(0, i) : test; } opts.setSessionId(sessionid); if (test == null) { opts.addTestPath(sessionid); } else { opts.addTestPath(test); } for (Entry<String, String> entry : params.entrySet()) { if (entry.getKey().startsWith("profile_")) { String profileId = entry.getValue(); int i = profileId.indexOf("}"); opts.addTestPath(sessionid + "/" + profileId.substring(i + 1)); } } s.load(logdir, sessionid); opts.setSourcesName(s.getSourcesName()); } else if (mode.equals("resume")) { opts.setMode(Test.RESUME_MODE); String sessionid = params.get("session"); opts.setSessionId(sessionid); s.load(logdir, sessionid); opts.setSourcesName(s.getSourcesName()); } else { opts.setMode(Test.TEST_MODE); String sessionid = LogUtils.generateSessionId(logdir); s.setSessionId(sessionid); String sources = params.get("sources"); s.setSourcesName(sources); SuiteEntry suite = conf.getSuites().get(sources); s.setSuiteName(suite.getId()); // String suite = params.get("suite"); // s.setSuiteName(suite); String description = params.get("description"); s.setDescription(description); opts.setSessionId(sessionid); opts.setSourcesName(sources); opts.setSuiteName(suite.getId()); ArrayList<String> profiles = new ArrayList<String>(); for (Entry<String, String> entry : params.entrySet()) { if (entry.getKey().startsWith("profile_")) { profiles.add(entry.getValue()); opts.addProfile(entry.getValue()); } } s.setProfiles(profiles); s.save(logdir); } String webdir = conf.getWebDirs().get(s.getSourcesName()); // String requestURI = request.getRequestURI(); // String contextPath = requestURI.substring(0, requestURI.indexOf(request.getServletPath()) + 1); // URI contextURI = new URI(request.getScheme(), null, request.getServerName(), request.getServerPort(), contextPath, null, null); URI contextURI = new URI(request.getScheme(), null, request.getServerName(), request.getServerPort(), request.getRequestURI(), null, null); opts.setBaseURI(new URL(contextURI.toURL(), webdir + "/").toString()); // URI baseURI = new URL(contextURI.toURL(), webdir).toURI(); // String base = baseURI.toString() + URLEncoder.encode(webdir, "UTF-8") + "/"; // opts.setBaseURI(base); //System.out.println(opts.getSourcesName()); TECore core = new TECore(engine, indexes.get(opts.getSourcesName()), opts); //System.out.println(indexes.get(opts.getSourcesName()).toString()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); core.setOut(ps); core.setWeb(true); Thread thread = new Thread(core); session.setAttribute("testsession", core); thread.start(); response.setContentType("text/xml"); out.println("<thread id=\"" + thread.getId() + "\" sessionId=\"" + s.getSessionId() + "\"/>"); } else if (operation.equals("Stop")) { response.setContentType("text/xml"); TECore core = (TECore) session.getAttribute("testsession"); if (core != null) { core.stopThread(); session.removeAttribute("testsession"); out.println("<stopped/>"); } else { out.println("<message>Could not retrieve core object</message>"); } } else if (operation.equals("GetStatus")) { TECore core = (TECore) session.getAttribute("testsession"); response.setContentType("text/xml"); out.print("<status"); if (core.getFormHtml() != null) { out.print(" form=\"true\""); } if (core.isThreadComplete()) { out.print(" complete=\"true\""); session.removeAttribute("testsession"); } out.println(">"); out.print("<![CDATA["); // out.print(core.getOutput()); out.print(URLEncoder.encode(core.getOutput(), "UTF-8").replace('+', ' ')); out.println("]]>"); out.println("</status>"); } else if (operation.equals("GetForm")) { TECore core = (TECore) session.getAttribute("testsession"); String html = core.getFormHtml(); core.setFormHtml(null); response.setContentType("text/html"); out.print(html); } else if (operation.equals("SubmitForm")) { TECore core = (TECore) session.getAttribute("testsession"); Document doc = DB.newDocument(); Element root = doc.createElement("values"); doc.appendChild(root); for (String key : params.keySet()) { if (!key.startsWith("te-")) { Element valueElement = doc.createElement("value"); valueElement.setAttribute("key", key); valueElement.appendChild(doc.createTextNode(params.get(key))); root.appendChild(valueElement); } } if (multipart) { Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField() && !item.getName().equals("")) { File uploadedFile = new File(core.getLogDir(), StringUtils.getFilenameFromString(item.getName())); item.write(uploadedFile); Element valueElement = doc.createElement("value"); String key = item.getFieldName(); valueElement.setAttribute("key", key); if (core.getFormParsers().containsKey(key)) { Element parser = core.getFormParsers().get(key); URL url = uploadedFile.toURI().toURL(); Element resp = core.parse(url.openConnection(), parser, doc); Element content = DomUtils.getElementByTagName(resp, "content"); if (content != null) { Element child = DomUtils.getChildElement(content); if (child != null) { valueElement.appendChild(child); } } } else { Element fileEntry = doc.createElementNS(CTL_NS, "file-entry"); fileEntry.setAttribute("full-path", uploadedFile.getAbsolutePath().replace('\\', '/')); fileEntry.setAttribute("media-type", item.getContentType()); fileEntry.setAttribute("size", String.valueOf(item.getSize())); valueElement.appendChild(fileEntry); } root.appendChild(valueElement); } } } core.setFormResults(doc); response.setContentType("text/html"); out.println("<html>"); out.println("<head><title>Form Submitted</title></head>"); out.print("<body onload=\"window.parent.update()\"></body>"); out.println("</html>"); } } catch (Throwable t) { throw new ServletException(t); } }