List of usage examples for java.lang Thread getName
public final String getName()
From source file:dr.app.bss.Utils.java
private static void showExceptionDialog(Thread t, Throwable e) { String msg = String.format("Unexpected problem on thread %s: %s", t.getName(), e.getMessage()); logException(t, e);/*from w ww . ja v a2 s . c o m*/ JOptionPane.showMessageDialog(Utils.getActiveFrame(), // msg, // "Error", // JOptionPane.ERROR_MESSAGE, // Utils.createImageIcon(Utils.ERROR_ICON)); }
From source file:majordodo.task.BrokerTestUtils.java
@Before public void brokerTestUtilsBefore() throws Exception { // Setup exception handler Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override//from w ww . j av a 2 s.c om public void uncaughtException(Thread t, Throwable e) { System.err.println("uncaughtException from thread " + t.getName() + ": " + e); e.printStackTrace(); unhandledExceptions.add(e); } }); // Setup Logger System.out.println("Setup logger to level " + logLevel.getName()); java.util.logging.LogManager.getLogManager().reset(); ConsoleHandler ch = new ConsoleHandler(); ch.setLevel(logLevel); ch.setFormatter(new Formatter() { @Override public String format(LogRecord record) { return "" + new java.sql.Timestamp(record.getMillis()) + " " + record.getLevel() + " [" + getThreadName(record.getThreadID()) + "<" + record.getThreadID() + ">] " + record.getLoggerName() + ": " + formatMessage(record) + "\n"; } }); java.util.logging.Logger.getLogger("").setLevel(logLevel); java.util.logging.Logger.getLogger("").addHandler(ch); // Initialize groupsMap groupsMap.clear(); groupsMap.put(userId, group); // Setup workdir Path mavenTargetDir = Paths.get("target").toAbsolutePath(); workDir = Files.createTempDirectory(mavenTargetDir, "test" + System.nanoTime()); if (startBroker) { broker = new Broker(brokerConfig, new FileCommitLog(workDir, workDir, 1024 * 1024), new TasksHeap(1000, createTaskPropertiesMapperFunction())); broker.startAsWritable(); server = new NettyChannelAcceptor(broker.getAcceptor()); server.start(); } if (startReplicatedBrokers) { zkServer = new ZKTestEnv(folderZk.getRoot().toPath()); zkServer.startBookie(); // Broker 1 broker1 = new Broker(broker1Config, new ReplicatedCommitLog(zkServer.getAddress(), zkServer.getTimeout(), zkServer.getPath(), folderSnapshots.newFolder().toPath(), BrokerHostData.formatHostdata( new BrokerHostData(broker1Host, broker1Port, "", false, null)), false), new TasksHeap(1000, createTaskPropertiesMapperFunction())); broker1.startAsWritable(); server1 = new NettyChannelAcceptor(broker1.getAcceptor(), broker1Host, broker1Port); server1.start(); // Broker 2 broker2 = new Broker(broker2Config, new ReplicatedCommitLog(zkServer.getAddress(), zkServer.getTimeout(), zkServer.getPath(), folderSnapshots.newFolder().toPath(), BrokerHostData.formatHostdata( new BrokerHostData(broker2Host, broker2Port, "", false, null)), false), new TasksHeap(1000, createTaskPropertiesMapperFunction())); broker2.start(); server2 = new NettyChannelAcceptor(broker2.getAcceptor(), broker2Host, broker2Port); server2.start(); // Broker locator brokerLocator = new ZKBrokerLocator(zkServer.getAddress(), zkServer.getTimeout(), zkServer.getPath()); } }
From source file:gash.router.app.DemoApp.java
/** * Get the context of the thread from which it is called ***//*from www. j av a 2 s .c o m*/ public void run() { Thread currentThread = Thread.currentThread(); int startBlockNo; int endBlockNo; /*** * Split the file read into two halves to be processed by two different * concurrent processes */ if (currentThread.getName() == "firstHalf") { startBlockNo = 0; endBlockNo = (msg.getDuty().getNumOfBlocks() / 2) - 1; System.out.println("Thread: " + currentThread.getName() + "has blocks starting:" + startBlockNo + "ending blocking as :" + endBlockNo); readFileFromBlocks(fileBlocksList, msg, startBlockNo, endBlockNo, currentThread.getName()); } else { startBlockNo = (msg.getDuty().getNumOfBlocks() / 2); endBlockNo = msg.getDuty().getNumOfBlocks() - 1; System.out.println("Thread: " + currentThread.getName() + "has blocks starting:" + startBlockNo + "ending blocking as :" + endBlockNo); readFileFromBlocks(fileBlocksList, msg, startBlockNo, endBlockNo, currentThread.getName()); } }
From source file:org.openstreetmap.josm.data.cache.JCSCachedTileLoaderJob.java
@Override public void run() { final Thread currentThread = Thread.currentThread(); final String oldName = currentThread.getName(); currentThread.setName("JCS Downloading: " + getUrlNoException()); LOG.log(Level.FINE, "JCS - starting fetch of url: {0} ", getUrlNoException()); ensureCacheElement();//from w w w .j a v a2 s .c o m try { // try to fetch from cache if (!force && cacheElement != null && isCacheElementValid() && isObjectLoadable()) { // we got something in cache, and it's valid, so lets return it LOG.log(Level.FINE, "JCS - Returning object from cache: {0}", getCacheKey()); finishLoading(LoadResult.SUCCESS); return; } // try to load object from remote resource if (loadObject()) { finishLoading(LoadResult.SUCCESS); } else { // if loading failed - check if we can return stale entry if (isObjectLoadable()) { // try to get stale entry in cache finishLoading(LoadResult.SUCCESS); LOG.log(Level.FINE, "JCS - found stale object in cache: {0}", getUrlNoException()); } else { // failed completely finishLoading(LoadResult.FAILURE); } } } finally { executionFinished(); currentThread.setName(oldName); } }
From source file:nlp.mediawiki.parser.MultistreamBzip2XmlDumpParser.java
@Override public void run() { final AtomicBoolean terminate = new AtomicBoolean(false); final Logger logger = LoggerFactory.getLogger(MultistreamBzip2XmlDumpParser.class); //1. Start all worker threads for (int i = 0; i < workers.length; i++) { workers[i] = new Worker(); workers[i].setName("Dump Worker " + i); }/* w w w . j a va 2 s. co m*/ //Add an uncaught exception handler and allow for a graceful shutdown. Thread.UncaughtExceptionHandler h = new Thread.UncaughtExceptionHandler() { public void uncaughtException(Thread th, Throwable ex) { logger.error("Fatal error in thread {}, terminating...", th.getName(), ex); for (Worker worker : workers) { worker.interrupt(); } terminate.set(true); } }; for (Worker worker : workers) { worker.setUncaughtExceptionHandler(h); worker.start(); } //2. Seed them with data until there is no more PageBlock data; while ((data = pageReader.next()) != null && !terminate.get()) { try { blocks.put(data); } catch (InterruptedException e) { logger.error("Data put interrupted", e); break; } } for (int i = 0; i < workers.length; i++) { try { blocks.put(new PageBlock(null, null)); } catch (InterruptedException e) { logger.info("Termination interrupted", e); break; } } //3. Await termination of all workers for (Worker worker : workers) { try { worker.join(); } catch (InterruptedException e) { logger.error("Worker {} thread interrupted.", worker.getName(), e); } } output(Collections.<Page>emptyList()); }
From source file:dr.app.bss.Utils.java
private static void showExceptionDialog(Thread t, Throwable e, String message) { String msg = String.format("Unexpected problem on thread %s: %s" + "\n" + message, t.getName(), e.getMessage());//from ww w . ja va2 s. c om logException(t, e); JOptionPane.showMessageDialog(Utils.getActiveFrame(), // msg, // "Error", // JOptionPane.ERROR_MESSAGE, // Utils.createImageIcon(Utils.ERROR_ICON)); }
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++;/* ww w .j a v a 2s .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.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))); }//from www.j a v a 2 s . co m 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.apache.hadoop.fs.azure.PageBlobOutputStream.java
private void logAllStackTraces() { Map liveThreads = Thread.getAllStackTraces(); for (Iterator i = liveThreads.keySet().iterator(); i.hasNext();) { Thread key = (Thread) i.next(); LOG.debug("Thread " + key.getName()); StackTraceElement[] trace = (StackTraceElement[]) liveThreads.get(key); for (int j = 0; j < trace.length; j++) { LOG.debug("\tat " + trace[j]); }//from w w w. j av a2 s . com } }
From source file:org.alfresco.repo.transaction.ConnectionPoolOverloadTest.java
@Test public void testOverload() throws Exception { List<Thread> threads = new LinkedList<Thread>(); int numThreads = dbPoolMax + 1; int i = 0;//from w ww .j a va 2 s.co m try { for (i = 0; i < numThreads; i++) { Thread thread = new TxnThread("Thread-" + i); thread.start(); threads.add(thread); } } finally { try { for (Thread thread : threads) { if (thread != null) { try { thread.join(dbPoolWaitMax); } catch (Exception e) { fail("The " + thread.getName() + " failed to join."); } } } } finally { for (Thread thread : threads) { if (thread != null) { thread.interrupt(); } } } assertTrue("The number of failed threads should not be 0.", failCount.intValue() > 0); assertTrue( "The number of open transactions should not be more that the db pool maximum." + "(Maybe a configuration of DB connection limit is less then db.pool.max)" + " db.pool.max is " + dbPoolMax + ", number of threads is " + numThreads + ", number of failed threads is" + failCount.intValue(), dbPoolMax >= numThreads - failCount.intValue()); } }