@SuppressWarnings("deprecation") @PreDestroy private void cleanUp() throws Exception { // TODO Maybe Spring is better at handling these? log.info("\nClean up " + this.getClass().getSimpleName() + " (4) : "); // Shutdown the proxy if needed if (proxy != null) { proxy.shutdown(); } log.info("1 "); // Kill the message pump from within messageQueue.clear(); putMessage(TournamentEvent.QUIT); messageFeeder.join(); log.info("2 "); // Kill the state machine from within eventQueue.clear(); putEvent(TournamentEvent.QUIT); stateRunner.join(); log.info("3 "); for (Thread t : Thread.getAllStackTraces().keySet()) { if (t.getName().contains("Timer-") || t.getName().contains("ActiveMQ")) { synchronized (t) { t.stop(); } } } log.info("4\n"); }
static void verifyThreadTerminated(Thread thread, long millis) throws InterruptedException { thread.join(millis); if (thread.isAlive()) { LOG.error("Thread " + thread.getName() + " : " + Arrays.toString(thread.getStackTrace())); Assert.assertFalse("thread " + thread.getName() + " still alive after join", true); } }
/** * @param args * @throws InterruptedException */ public static void main(String[] args) throws InterruptedException { Thread t1 = new Thread() { @Override public void run() { long i = 0l; try { while (this.isInterrupted() == false) { System.out.println(Thread.currentThread().getName() + " sleep 10 "); TimeUnit.SECONDS.sleep(10); } } catch (InterruptedException e) // 会抛出InterruptException因为Sleep会阻塞 { e.printStackTrace(); System.out.println(Thread.currentThread().getName() + ":" + e.getMessage()); } } }; Thread t2 = new Thread() { @Override public void run() { long i = 0l; while (this.isInterrupted() == false) { try { Thread.currentThread().sleep(1); i++; while (true) { i++; } } catch (InterruptedException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } } } }; t1.start(); t2.start(); System.out.println( t1.getName() + " before interupt:" + t1.isInterrupted() + " is alive=" + t1.isAlive()); System.out.println( t2.getName() + " before interupt:" + t2.isInterrupted() + " is alive=" + t2.isAlive()); TimeUnit.SECONDS.sleep(1); t1.interrupt(); t2.interrupt(); TimeUnit.SECONDS.sleep(1); System.out.println( t1.getName() + " after interupt:" + t1.isInterrupted() + " is alive=" + t1.isAlive()); System.out.println( t2.getName() + " after interupt:" + t2.isInterrupted() + " is alive=" + t2.isAlive()); }
private String stringFromTracesAndNames( Map<Thread, StackTraceElement[]> traces, Map<Thread, String> names) { String trace = null; if (traces != null) { String capturedThreadName = null; if (names == null) { capturedThreadName = Thread.currentThread().getName(); } else { capturedThreadName = names.get(Thread.currentThread()); } StringBuilder sb = new StringBuilder(); sb.append("\nRequest Thread Name: ").append(capturedThreadName).append("\n\n"); for (Iterator iterator = traces.keySet().iterator(); iterator.hasNext(); ) { Thread t = (Thread) iterator.next(); StackTraceElement stack[] = traces.get(t); String name = t.getName() != null ? t.getName() : "No name"; String groupName = t.getThreadGroup() != null ? t.getThreadGroup().getName() : "No group"; if (stack != null && stack.length > 2 && !name.equals("main") && !name.equals("ERXStopWatchTimer") && !groupName.equals("system")) { StackTraceElement func = stack[0]; if (func != null && func.getClassName() != null && !func.getClassName().equals("java.net.PlainSocketImpl")) { if (names != null) { String customThreadName = names.get(t); if (customThreadName != null) { sb.append(customThreadName).append(":\n"); } } sb.append(t).append(":\n"); for (int i = 0; i < stack.length; i++) { StackTraceElement stackTraceElement = stack[i]; sb.append("\tat ").append(stackTraceElement).append('\n'); } } } } sb.insert(0, '\n'); trace = sb.toString(); // trace = // trace.replaceAll("at\\s+(com.webobjects|java|er|sun)\\..*?\\n", // "...\n"); // trace = trace.replaceAll("(\t\\.\\.\\.\n+)+", "\t...\n"); } else { trace = ""; } return trace; }
public static void main(String[] args) { System.out.println("main method"); Thread th = Thread.currentThread(); System.out.println("Original thread name: " + th.getName()); System.out.println("Original thread priority: " + th.getPriority()); th.setName("main-thread"); th.setPriority(7); System.out.println("Changed thread name: " + th.getName()); System.out.println("Changed thread priority: " + th.getPriority()); }
protected void waitForSentNewsletter() throws Exception { Thread[] threads = new Thread[40]; Thread.enumerate(threads); for (int i = 0; i < threads.length; i++) { Thread currentThread = threads[i]; if (currentThread != null && (currentThread .getName() .startsWith(JpnewsletterSystemConstants.NEWSLETTER_SENDER_THREAD_NAME) || currentThread .getName() .startsWith(JpnewsletterSystemConstants.EMAIL_SENDER_NAME_THREAD_PREFIX))) { currentThread.join(); } } }
@Test public void testThreadDetails() { final AtomicReference<Thread> threadRef = new AtomicReference<Thread>(); SingleThreadEventExecutor executor = new SingleThreadEventExecutor(null, Executors.newCachedThreadPool(), false) { @Override protected void run() { threadRef.set(Thread.currentThread()); while (!confirmShutdown()) { Runnable task = takeTask(); if (task != null) { task.run(); } } } }; ThreadProperties threadProperties = executor.threadProperties(); Assert.assertSame(threadProperties, executor.threadProperties()); Thread thread = threadRef.get(); Assert.assertEquals(thread.getId(), threadProperties.id()); Assert.assertEquals(thread.getName(), threadProperties.name()); Assert.assertEquals(thread.getPriority(), threadProperties.priority()); Assert.assertEquals(thread.getState(), threadProperties.state()); Assert.assertEquals(thread.isAlive(), threadProperties.isAlive()); Assert.assertEquals(thread.isDaemon(), threadProperties.isDaemon()); Assert.assertEquals(thread.isInterrupted(), threadProperties.isInterrupted()); Assert.assertTrue(threadProperties.stackTrace().length > 0); executor.shutdownGracefully(); }
@Override protected void afterExecute(Runnable r, Throwable t) { super.afterExecute(r, t); Thread thread = (Thread) r; runningThreadNames.remove(thread.getName()); logger.debug("{} ===================> Finished.", thread.getName()); }
@Override public void uncaughtException(Thread t, Throwable thrw) { // log warning for the exception StringWriter s = new StringWriter(); s.write("Uncaught exception in thread " + t.getName() + ":\n"); PrintWriter w = new PrintWriter(s); thrw.printStackTrace(w); log.warn(s.toString()); try { s.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // resume work Thread th = new Thread(this, "Rxthread " + this.id); th.setDaemon(true); th.setUncaughtExceptionHandler(this); synchronized (currentTrainingRun.threads) { log.warn("Resuming thread " + t.getName() + " with " + th.getName()); currentTrainingRun.threads.add(th); // don't want to join before thread has been started th.start(); } }
public static void main(String[] args) { Thread t1 = new Thread(new Car("AAA", 10L, true)); Thread t2 = new Thread(new Car("BBB", 20L, false)); t1.setName("AAA"); t2.setName("BBB"); t1.start(); t2.start(); String winner = null; try { while (true) { Thread.sleep(100); if (!t1.isAlive() && t2.isAlive()) { winner = t1.getName(); } if (!t2.isAlive() && t1.isAlive()) { winner = t2.getName(); } if (!(t1.isAlive() || t2.isAlive())) { System.out.println("Winner is " + winner + "!"); break; } } } catch (InterruptedException e) { } }
@Override public void uncaughtException(Thread t, Throwable e) { /* In case of fatal errors we shut down. The wrapper script * will restart the domain. Notice that there is no guarantee * that the fatal error will not reoccur during shutdown and * in that case the shutdown may fail. We may want to consider * refining the shutdown logic such that in recovers if the * fatal error reoccurs. */ if (e instanceof VirtualMachineError) { _oomSafetyBuffer = null; kill(); _log.error( AlarmMarkerFactory.getMarker( PredefinedAlarm.FATAL_JVM_ERROR, getCellDomainName(), getCellName()), "Restarting due to fatal JVM error", e); return; } Throwable root = Throwables.getRootCause(e); if (root instanceof FileNotFoundException) { if (root.getMessage().contains("Too many open files")) { _log.error( AlarmMarkerFactory.getMarker( PredefinedAlarm.OUT_OF_FILE_DESCRIPTORS, getCellDomainName(), getCellName()), "Uncaught exception in thread " + t.getName(), e); return; } } _log.error("Uncaught exception in thread " + t.getName(), e); }
public void execute(Thread command) { if (runningThreadNames.contains(command.getName())) { logger.warn("{} ===================> Running.", command.getName()); return; } logger.debug("{} ===================> Started.", command.getName()); super.execute(command); }
public void run() { for (int i = 0; i < 10; i++) { System.out.println(i + " " + thread.getName()); try { thread.sleep((long) (Math.random() * 1000)); } catch (InterruptedException e) { } } System.out.println("DONE! " + thread.getName()); }
/** * Traverse the ThreadGroups threads and its child ThreadGroups printing information for each * thread found. If 'threadName' is non-null, only print information for the thread that matches * the name. * * @param grp the ThreadGroup to traverse * @param out the destination for output * @param threadName if non-null, only display this thread. */ private void showThreads(ThreadGroup grp, PrintWriter out, String threadName) { if (threadName == null) { out.println(GROUP + grp.getName()); } final int max = grp.activeCount() * 2; final Thread[] ts = new Thread[max]; grp.enumerate(ts); for (int i = 0; i < max; i++) { final Thread t = ts[i]; if (t != null) { if ((threadName == null) || threadName.equals(t.getName())) { VmThread vmThread = AccessController.doPrivileged( new PrivilegedAction<VmThread>() { public VmThread run() { return ThreadHelper.getVmThread(t); } }); out.println( SLASH_T + t.getId() + SEPARATOR + t.getName() + SEPARATOR + t.getPriority() + SEPARATOR + vmThread.getThreadStateName()); if (threadName != null) { final Object[] trace = VmThread.getStackTrace(vmThread); final int traceLen = trace.length; out.println(SLASH_T + SLASH_T + TRACE); for (int k = 0; k < traceLen; k++) { out.println(SLASH_T + SLASH_T + trace[k]); } return; } } } } final int gmax = grp.activeGroupCount() * 2; final ThreadGroup[] tgs = new ThreadGroup[gmax]; grp.enumerate(tgs); for (int i = 0; i < gmax; i++) { final ThreadGroup tg = tgs[i]; if (tg != null) { showThreads(tg, out, threadName); } } }
public static void main(String[] args) throws IOException, InterruptedException { Thread t = new Thread(new ContentGatherer()); System.out.println("starting :" + t.getName()); t.start(); Thread.sleep(3000); Thread t2 = new Thread(new ContentGatherer()); System.out.println("starting :" + t2.getName()); t2.start(); Thread t3 = new Thread(new ContentWriter()); System.out.println("starting :" + t3.getName()); t3.start(); Thread t4 = new Thread(new ContentWriter()); System.out.println("starting :" + t4.getName()); t4.start(); }
public void insert(Thread thread) throws InterruptedException { lock.lockInterruptibly(); // 注意,如果需要正确中断等待锁的线程,必须将获取锁放在外面,然后将InterruptedException抛出 try { System.out.println(thread.getName() + "得到了锁"); long startTime = System.currentTimeMillis(); for (; ; ) { if (System.currentTimeMillis() - startTime >= Integer.MAX_VALUE) break; // 插入数据 } } finally { System.out.println(Thread.currentThread().getName() + "执行finally"); lock.unlock(); System.out.println(thread.getName() + "释放了锁"); } }
public synchronized String format(LogRecord record) { StringBuffer sb = new StringBuffer(); date.setTime(record.getMillis() + timeDiff); sb.append(dFormat.format(date)); if (isShowingThreads) { Thread currentThread = Thread.currentThread(); if (currentThread != lastThread) { lastThread = currentThread; lastThreadName = currentThread.getName(); } sb.append(" [").append(lastThreadName).append(']'); } sb.append(' ') .append(record.getLevel()) .append(' ') .append(getAliasFor(record.getLoggerName())) .append('|') .append(record.getMessage()) .append(EOL); if (record.getThrown() != null) { try { StringWriter out = new StringWriter(); PrintWriter pout = new PrintWriter(out); record.getThrown().printStackTrace(pout); pout.close(); sb.append(out.toString()); } catch (Exception e) { // Ignore any errors while extracting stack trace } } return sb.toString(); }
private void showDefaultInfo(ThreadGroup grp) { TreeSet<Thread> threadSet = new TreeSet<Thread>( new Comparator<Thread>() { @Override public int compare(Thread t1, Thread t2) { return Long.valueOf(t1.getId()).compareTo(t2.getId()); } }); findThreads(grp, threadSet); PrintWriter out = getOutput().getPrintWriter(); for (final Thread thread : threadSet) { VmThread vmThread = AccessController.doPrivileged( new PrivilegedAction<VmThread>() { public VmThread run() { return ThreadHelper.getVmThread(thread); } }); out.println( " " + thread.getId() + SEPARATOR + thread.getName() + SEPARATOR + thread.getPriority() + SEPARATOR + vmThread.getThreadStateName()); } }
/** Return a thread. */ @Override public Thread newThread(Runnable r) { if (shutdown) return null; Runnable wrapper = new Runnable() { /** Keep track of non-daemon threads so shutdown can wait for their termination. */ @Override public void run() { threads.fromNewToRunning(Thread.currentThread()); r.run(); /* If the task has thrown an exception, the code below is * not getting executed. The uncaughtException this.handler * removes the thread from the tracker list and notifies * the completer. */ threads.removeRunning(Thread.currentThread()); if (!hasActiveNonDaemonThreads()) completer.accept(ThreadFactoryTracker.this, null); } }; Thread t = factory.newThread(wrapper); t.setName(t.getName() + "-" + threadName); t.setUncaughtExceptionHandler(handler); threads.addNew(t); return t; }
/** * {@inheritDoc} * * @throws Exception */ @Override @After public void tearDown() throws Exception { if (manager1 != null) { manager1.shutdown(); } if (manager2 != null) { manager2.shutdown(); } if (manager3 != null) { manager3.shutdown(); } if (manager4 != null) { manager4.shutdown(); } if (manager5 != null) { manager5.shutdown(); } if (manager6 != null) { manager6.shutdown(); } Thread.sleep(2000); List threads = enumerateThreads(); for (int i = 0; i < threads.size(); i++) { Thread thread = (Thread) threads.get(i); if (thread.getName().equals("Replication Thread")) { fail("There should not be any replication threads running after shutdown"); } } }
public void consumir(Thread thr) throws InterruptedException { vacio.acquire(); mutex.acquire(); buffer[salida] = 0; System.out.println("Hebraconsumidora: " + thr.getName() + " consume en posición: " + salida); Productorconsumidor.mostrar.setText( Productorconsumidor.mostrar.getText() + "Productor consume " + "\n"); salida = (salida + 1) % buffer.length; contador = contador - 1; System.out.println("Consumidor consume "); for (int i = 0; i < buffer.length; i++) { System.out.print("[" + buffer[i] + "]"); } for (int i = 0; i < buffer.length; i++) { Productorconsumidor.mostrar.setText( Productorconsumidor.mostrar.getText() + "[" + buffer[i] + "]"); } Productorconsumidor.mostrar.setText(Productorconsumidor.mostrar.getText() + "\n"); System.out.print("\n"); mutex.release(); lleno.release(); }
@Override public void run() { while (true) { log("Running check"); long pre = TimeService.nanoTime(); Map<Thread, StackTraceElement[]> stacks = Thread.getAllStackTraces(); long post = TimeService.nanoTime(); log("Thread.getAllStackTraces() took " + (post - pre) + " nanoseconds"); for (Thread t : stacks.keySet()) { String name = t.getName(); if (!name.equals(WATCHDOG) && (mask == null || name.contains(mask))) { StackTraceElement[] stack = stacks.get(t); if (stack.length < shortStack) { continue; } boolean stuck = isStuck(t, stack); if (!onlyStuck || stuck) { traceStack(t, stack, stuck); } } } lastStacks = stacks; try { Thread.sleep(period); } catch (InterruptedException e) { log.error("Thread has been interrupted", e); Thread.currentThread().interrupt(); } } }
public static void main(String[] args) { MyLock locker = new MyLock(); Thread[] threads = new Thread[5]; for (int i = 0; i < 5; i++) { threads[i] = new Thread(new MyTask(locker)); threads[i].start(); } for (int i = 0; i < 15; i++) { System.out.println("===========Logging the Lock info=========="); System.out.println("Lock Owner: " + locker.getOwnerName()); System.out.println("Lock has the queued threads: " + locker.hasQueuedThreads()); if (locker.hasQueuedThreads()) { System.out.println(locker.getQueueLength()); Collection<Thread> ct = locker.getThreads(); for (Thread t : ct) { System.out.println(t.getName()); } } System.out.println("Fairness: " + locker.isFair()); System.out.println("Lock is locked: " + locker.isLocked()); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } }
public void contextDestroyed(ServletContextEvent sce) { // This manually deregisters JDBC driver, which prevents Tomcat 7 from complaining about memory // leaks wrto this class Enumeration<Driver> drivers = DriverManager.getDrivers(); while (drivers.hasMoreElements()) { Driver driver = drivers.nextElement(); try { DriverManager.deregisterDriver(driver); LOG.info(String.format("deregistering jdbc driver: %s", driver)); } catch (SQLException e) { LOG.warn(String.format("Error deregistering driver %s", driver), e); } } // Try to kill the TOMCAT abandoned connection clean up thread // to prevent it from holding the whole context in memory causing // a leak Set<Thread> threadSet = Thread.getAllStackTraces().keySet(); Thread[] threadArray = threadSet.toArray(new Thread[threadSet.size()]); for (Thread t : threadArray) { if (t.getName().contains("Abandoned connection cleanup thread")) { synchronized (t) { t.stop(); // don't complain, it works } } } }
@Override public void run() { Thread current = Thread.currentThread(); String name = current.getName(); current.setName(name + "-acceptor-" + _acceptor + "-" + AbstractConnector.this); synchronized (AbstractConnector.this) { _acceptors[_acceptor] = current; } try { while (isAccepting()) { try { accept(_acceptor); } catch (Throwable e) { if (isAccepting()) LOG.warn(e); else LOG.debug(e); } } } finally { current.setName(name); synchronized (AbstractConnector.this) { _acceptors[_acceptor] = null; } _stopping.countDown(); } }
@Override public void getInfo(PrintWriter pw) { pw.append(" CellDomainName = ").println(getCellDomainName()); pw.format( " I/O rcv=%d;asw=%d;frw=%d;rpy=%d;exc=%d\n", _packetsReceived, _packetsAnswered, _packetsForwarded, _packetsReplied, _exceptionCounter); long fm = _runtime.freeMemory(); long tm = _runtime.totalMemory(); pw.format(" Memory : tot=%d;free=%d;used=%d\n", tm, fm, tm - fm); pw.println(" Cells (Threads)"); for (String name : _nucleus.getCellNames()) { pw.append(" ").append(name).append("("); Thread[] threads = _nucleus.getThreads(name); if (threads != null) { boolean first = true; for (Thread thread : threads) { pw.print(thread.getName()); if (first) { first = false; } else { pw.print(","); } } } pw.println(")"); } }
/** * Based on the default thread factory * * @param name the name prefix of the new thread * @return the factory to use when creating new threads */ public static final ThreadFactory getThreadFactory(String name) { return r -> { Thread t = Executors.defaultThreadFactory().newThread(r); t.setName(name + "-" + t.getName()); // $NON-NLS-1$ return t; }; }
/** * Names a thread according to base_name, cluster name and local address. If includeClusterName * and includeLocalAddress are null, but cluster_name is set, then we assume we have a shared * transport and name the thread shared=clusterName. In the latter case, clusterName points to the * singleton_name of TP. * * @param base_name * @param thread * @param addr * @param cluster_name */ public void renameThread(String base_name, Thread thread, String addr, String cluster_name) { if (thread == null) return; StringBuilder sb = new StringBuilder(base_name != null ? base_name : thread.getName()); if (use_numbering) { short id; synchronized (this) { id = ++counter; } sb.append("-" + id); } if (cluster_name == null) cluster_name = clusterName; if (addr == null) addr = this.address; if (!includeClusterName && !includeLocalAddress && cluster_name != null) { sb.append(",shared=").append(cluster_name); thread.setName(sb.toString()); return; } if (includeClusterName) sb.append(',').append(cluster_name); if (includeLocalAddress) sb.append(',').append(addr); if (use_numbering || includeClusterName || includeLocalAddress) thread.setName(sb.toString()); }
public Map<ConcreteResource, CharSequence> getActiveLocks() { final Map<ConcreteResource, CharSequence> active = new HashMap<ConcreteResource, CharSequence>(); for (final ConcreteResource f : lock.keySet()) { final StringBuilder owner = new StringBuilder(); final WeakReference<Thread> ref = lock.get(f); if (ref == null) { owner.append("UNKNOWN OWNER; REF IS NULL."); } final Thread t = ref.get(); if (t == null) { owner.append("UNKNOWN OWNER; REF IS EMPTY."); } else { owner.append(t.getName()); if (!t.isAlive()) { owner.append(" (DEAD)"); } } active.put(f, owner); } return active; }
public void producir(Thread thr) throws InterruptedException { lleno.acquire(); mutex.acquire(); buffer[entrada] = 1; System.out.println("Hebraproductora: " + thr.getName() + " produce en posición: " + entrada); Productorconsumidor.mostrar.setText( Productorconsumidor.mostrar.getText() + "Productor produce " + "\n"); entrada = (entrada + 1) % buffer.length; contador = contador + 1; System.out.println("Productor produce "); for (int i = 0; i < buffer.length; i++) { System.out.print("[" + buffer[i] + "]"); } for (int i = 0; i < buffer.length; i++) { Productorconsumidor.mostrar.setText( Productorconsumidor.mostrar.getText() + "[" + buffer[i] + "]"); } Productorconsumidor.mostrar.setText(Productorconsumidor.mostrar.getText() + "\n"); System.out.print("\n"); mutex.release(); vacio.release(); }