Example usage for java.lang Thread getName

List of usage examples for java.lang Thread getName

Introduction

In this page you can find the example usage for java.lang Thread getName.

Prototype

public final String getName() 

Source Link

Document

Returns this thread's name.

Usage

From source file:ste.web.http.beanshell.BugFreeBeanShellHandler.java

@Test
public void runningMultipleThreadInDifferentContexts() throws Exception {
    final HttpSessionContext CTX1 = new HttpSessionContext();
    final HttpSessionContext CTX2 = new HttpSessionContext();
    CTX1.setAttribute(HttpCoreContext.HTTP_CONNECTION, getConnection());
    CTX2.setAttribute(HttpCoreContext.HTTP_CONNECTION, getConnection());
    Thread t1 = new Thread(new Runnable() {
        @Override//from   w  w  w .j a  va2 s.  c o m
        public void run() {
            try {
                handler.handle(get("/multithreading.bsh"), response, CTX1);
            } catch (Exception x) {
                x.printStackTrace();
            }
        }
    });
    Thread t2 = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                handler.handle(get("/multithreading.bsh"), response, CTX2);
            } catch (Exception x) {
                x.printStackTrace();
            }
        }
    });
    t1.start();
    t2.start();
    t1.join();
    t2.join();
    then(CTX1.get("view")).isEqualTo(t1.getName());
    then(CTX2.get("view")).isEqualTo(t2.getName());
}

From source file:org.apereo.portal.events.aggr.PortalRawEventsAggregatorImpl.java

@Override
@AggrEventsTransactional//from w  w  w.  j  ava  2  s .  co m
public EventProcessingResult doCloseAggregations() {
    if (!this.clusterLockService.isLockOwner(AGGREGATION_LOCK_NAME)) {
        throw new IllegalStateException("The cluster lock " + AGGREGATION_LOCK_NAME
                + " must be owned by the current thread and server");
    }

    final IEventAggregatorStatus cleanUnclosedStatus = eventAggregationManagementDao
            .getEventAggregatorStatus(IEventAggregatorStatus.ProcessingType.CLEAN_UNCLOSED, true);

    //Update status with current server name
    final String serverName = this.portalInfoProvider.getUniqueServerName();
    cleanUnclosedStatus.setServerName(serverName);
    cleanUnclosedStatus.setLastStart(new DateTime());

    //Determine date of most recently aggregated data
    final IEventAggregatorStatus eventAggregatorStatus = eventAggregationManagementDao
            .getEventAggregatorStatus(IEventAggregatorStatus.ProcessingType.AGGREGATION, false);
    if (eventAggregatorStatus == null || eventAggregatorStatus.getLastEventDate() == null) {
        //Nothing has been aggregated, skip unclosed cleanup

        cleanUnclosedStatus.setLastEnd(new DateTime());
        eventAggregationManagementDao.updateEventAggregatorStatus(cleanUnclosedStatus);

        return new EventProcessingResult(0, null, null, true);
    }

    final DateTime lastAggregatedDate = eventAggregatorStatus.getLastEventDate();

    //If lastCleanUnclosedDate is null use the oldest date dimension as there can be 
    //no aggregations that exist before it
    final DateTime lastCleanUnclosedDate;
    if (cleanUnclosedStatus.getLastEventDate() == null) {
        final DateDimension oldestDateDimension = this.dateDimensionDao.getOldestDateDimension();
        lastCleanUnclosedDate = oldestDateDimension.getDate().toDateTime();
    } else {
        lastCleanUnclosedDate = cleanUnclosedStatus.getLastEventDate();
    }

    if (!(lastCleanUnclosedDate.isBefore(lastAggregatedDate))) {
        logger.debug("No events aggregated since last unclosed aggregation cleaning, skipping clean: {}",
                lastAggregatedDate);
        return new EventProcessingResult(0, lastCleanUnclosedDate, lastAggregatedDate, true);
    }

    //Switch to flush on commit to avoid flushes during queries
    final EntityManager entityManager = this.getEntityManager();
    entityManager.flush();
    entityManager.setFlushMode(FlushModeType.COMMIT);

    //Track the number of closed aggregations and the last date of a cleaned interval
    int closedAggregations = 0;
    int cleanedIntervals = 0;
    DateTime cleanUnclosedEnd;

    final Thread currentThread = Thread.currentThread();
    final String currentName = currentThread.getName();
    try {
        currentThread.setName(currentName + "-" + lastCleanUnclosedDate + "-" + lastAggregatedDate);

        //Local caches used to reduce db io
        final IntervalsForAggregatorHelper intervalsForAggregatorHelper = new IntervalsForAggregatorHelper();
        final Map<AggregationInterval, AggregationIntervalInfo> previousIntervals = new HashMap<AggregationInterval, AggregationIntervalInfo>();

        //A DateTime within the next interval to close aggregations in
        DateTime nextIntervalDate = lastCleanUnclosedDate;
        do {
            //Reset our goal of catching up to the last aggregated event on every iteration
            cleanUnclosedEnd = lastAggregatedDate;

            //For each interval the aggregator supports, cleanup the unclosed aggregations
            for (final AggregationInterval interval : intervalsForAggregatorHelper.getHandledIntervals()) {
                final AggregationIntervalInfo previousInterval = previousIntervals.get(interval);
                if (previousInterval != null && nextIntervalDate.isBefore(previousInterval.getEnd())) {
                    logger.debug(
                            "{} interval before {} has already been cleaned during this execution, ignoring",
                            interval, previousInterval.getEnd());
                    continue;
                }

                //The END date of the last clean session will find us the next interval to clean
                final AggregationIntervalInfo nextIntervalToClean = intervalHelper.getIntervalInfo(interval,
                        nextIntervalDate);
                previousIntervals.put(interval, nextIntervalToClean);
                if (nextIntervalToClean == null) {
                    continue;
                }

                final DateTime start = nextIntervalToClean.getStart();
                final DateTime end = nextIntervalToClean.getEnd();
                if (!end.isBefore(lastAggregatedDate)) {
                    logger.debug("{} interval between {} and {} is still active, ignoring",
                            new Object[] { interval, start, end });
                    continue;
                }

                //Track the oldest interval end, this ensures that nothing is missed
                if (end.isBefore(cleanUnclosedEnd)) {
                    cleanUnclosedEnd = end;
                }

                logger.debug("Cleaning unclosed {} aggregations between {} and {}",
                        new Object[] { interval, start, end });

                for (final IntervalAwarePortalEventAggregator<PortalEvent> portalEventAggregator : intervalAwarePortalEventAggregators) {
                    checkShutdown();

                    final Class<? extends IPortalEventAggregator<?>> aggregatorType = getClass(
                            portalEventAggregator);

                    //Get aggregator specific interval info config
                    final AggregatedIntervalConfig aggregatorIntervalConfig = intervalsForAggregatorHelper
                            .getAggregatorIntervalConfig(aggregatorType);

                    //If the aggregator is being used for the specified interval call cleanUnclosedAggregations
                    if (aggregatorIntervalConfig.isIncluded(interval)) {
                        closedAggregations += portalEventAggregator.cleanUnclosedAggregations(start, end,
                                interval);
                    }
                }

                cleanedIntervals++;
            }

            //Set the next interval to the end date from the last aggregation run
            nextIntervalDate = cleanUnclosedEnd;

            logger.debug("Closed {} aggregations across {} interval before {} with goal of {}", new Object[] {
                    closedAggregations, cleanedIntervals, cleanUnclosedEnd, lastAggregatedDate });
            //Loop until either the batchSize of cleaned aggregations has been reached or no aggregation work is done
        } while (closedAggregations <= cleanUnclosedAggregationsBatchSize
                && cleanedIntervals <= cleanUnclosedIntervalsBatchSize
                && cleanUnclosedEnd.isBefore(lastAggregatedDate));
    } finally {
        currentThread.setName(currentName);
    }

    //Update the status object and store it
    cleanUnclosedStatus.setLastEventDate(cleanUnclosedEnd);
    cleanUnclosedStatus.setLastEnd(new DateTime());
    eventAggregationManagementDao.updateEventAggregatorStatus(cleanUnclosedStatus);

    return new EventProcessingResult(closedAggregations, lastCleanUnclosedDate, lastAggregatedDate,
            !cleanUnclosedEnd.isBefore(lastAggregatedDate));
}

From source file:org.lockss.util.Logger.java

String getThreadId(Thread thread) {
    String id;/*  ww  w.ja v  a 2 s .com*/
    synchronized (threadIds) {
        id = (String) threadIds.get(thread);
        if (id == null) {
            id = Integer.toString(++threadCtr);
            threadIds.put(thread, id);
            unannouncedName = thread.getName();
        }
    }
    // This recursive call MUST be AFTER the threadIds map is updated, and
    // AFTER setting unannouncedName to null
    if (unannouncedName != null) {
        String name = unannouncedName;
        unannouncedName = null;
        debug("ThreadId " + id + " is " + name);
        announcedName = name;
    }
    return id;
}

From source file:org.languagetool.gui.LanguageToolSupport.java

private void init() {
    try {//from  www. j  a  v a2  s  . c o  m
        config = new Configuration(new File(System.getProperty("user.home")), CONFIG_FILE, null);
    } catch (IOException ex) {
        throw new RuntimeException("Could not load configuration", ex);
    }

    Language defaultLanguage = config.getLanguage();
    if (defaultLanguage == null) {
        defaultLanguage = Languages.getLanguageForLocale(Locale.getDefault());
    }

    /**
     * Warm-up: we have a lot of lazy init in LT, which causes the first check to
     * be very slow (several seconds) for languages with a lot of data and a lot of
     * rules. We just assume that the default language is the language that the user
     * often uses and init the LT object for that now, not just when it's first used.
     * This makes the first check feel much faster:
     */
    reloadLanguageTool(defaultLanguage);

    checkExecutor = new ScheduledThreadPoolExecutor(1, new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setDaemon(true);
            t.setPriority(Thread.MIN_PRIORITY);
            t.setName(t.getName() + "-lt-background");
            return t;
        }
    });

    check = new AtomicInteger(0);

    this.textComponent.getDocument().addDocumentListener(new DocumentListener() {
        @Override
        public void insertUpdate(DocumentEvent e) {
            mustDetectLanguage = config.getAutoDetect();
            recalculateSpans(e.getOffset(), e.getLength(), false);
            if (backgroundCheckEnabled) {
                checkDelayed(null);
            }
        }

        @Override
        public void removeUpdate(DocumentEvent e) {
            mustDetectLanguage = config.getAutoDetect();
            recalculateSpans(e.getOffset(), e.getLength(), true);
            if (backgroundCheckEnabled) {
                checkDelayed(null);
            }
        }

        @Override
        public void changedUpdate(DocumentEvent e) {
            mustDetectLanguage = config.getAutoDetect();
            if (backgroundCheckEnabled) {
                checkDelayed(null);
            }
        }
    });

    mouseListener = new MouseListener() {
        @Override
        public void mouseClicked(MouseEvent me) {
        }

        @Override
        public void mousePressed(MouseEvent me) {
            if (me.isPopupTrigger()) {
                showPopup(me);
            }
        }

        @Override
        public void mouseReleased(MouseEvent me) {
            if (me.isPopupTrigger()) {
                showPopup(me);
            }
        }

        @Override
        public void mouseEntered(MouseEvent me) {
        }

        @Override
        public void mouseExited(MouseEvent me) {
        }
    };
    this.textComponent.addMouseListener(mouseListener);

    actionListener = e -> _actionPerformed(e);

    mustDetectLanguage = config.getAutoDetect();
    if (!this.textComponent.getText().isEmpty() && backgroundCheckEnabled) {
        checkImmediately(null);
    }
}

From source file:com.alfaariss.oa.sso.web.profile.logout.LogoutProfile.java

private LogoutState startListeners(ITGT tgt, ISession session, HttpServletRequest servletRequest)
        throws OAException {
    List<Thread> listThreads = new Vector<Thread>();
    //create threads
    LogoutState state = new LogoutState(_sessionFactory, session.getId());

    int iIndex = 0;
    for (ITGTListener listener : _tgtFactory.getListeners()) {
        iIndex++;//from w w w  . ja va2 s .  c o  m

        StringBuffer sbRunnableName = new StringBuffer(session.getId());
        sbRunnableName.append("_");
        sbRunnableName.append(iIndex);
        LogoutRunnable runnable = new LogoutRunnable(listener, tgt, state, sbRunnableName.toString());
        Thread tLogout = new Thread(runnable);

        StringBuffer sbThreadname = new StringBuffer("Logout (");
        sbThreadname.append(sbRunnableName.toString());
        sbThreadname.append(") - ");
        sbThreadname.append(tLogout.getName());
        tLogout.setName(sbThreadname.toString());
        listThreads.add(tLogout);
    }

    session.persist();

    _eventLogger.info(new UserEventLogItem(session, servletRequest.getRemoteAddr(),
            UserEvent.USER_LOGOUT_IN_PROGRESS, this, null));

    //start threads
    for (Thread thread : listThreads) {
        thread.start();
        _logger.debug("Started: " + thread.getName());
    }

    _logger.debug("Logout threads started");

    return state;
}

From source file:com.icesoft.util.ThreadFactory.java

public Thread newThread(final Runnable runnable) {
    Thread _thread;
    synchronized (lock) {
        _thread = new Thread(runnable, prefix + " [" + ++counter + "]");
    }//from   w w w.j av a  2 s  .  co  m
    _thread.setDaemon(daemon);
    try {
        /*
         * We attempt to set the context class loader because some J2EE
         * containers don't seem to set this properly, which leads to
         * important classes not being found. However, other J2EE containers
         * see this as a security violation.
         */
        _thread.setContextClassLoader(runnable.getClass().getClassLoader());
    } catch (SecurityException exception) {
        /*
         * If the current security policy does not allow this, we have to
         * hope that the appropriate class loader settings were transferred
         * to this new thread.
         */
        if (LOG.isTraceEnabled()) {
            LOG.trace("Setting the context class loader is not permitted.", exception);
        }
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("New thread: " + _thread.getName());
    }
    return _thread;
}

From source file:org.aitools.programd.Core.java

/**
 * Notes the given Throwable and advises that the Core may no longer be stable.
 * //  w  ww .  ja v  a 2 s . c  o  m
 * @param description the description of the Throwable
 * @param t the thread in which the Throwable was thrown
 * @param e the Throwable to log
 */
public void alert(String description, Thread t, Throwable e) {
    String throwableDescription = e.getClass().getSimpleName() + " in thread \"" + t.getName() + "\"";
    if (e.getMessage() != null) {
        throwableDescription += ": " + e.getMessage();
    } else {
        throwableDescription += ".";
    }
    this._logger.error("Core may no longer be stable due to " + description + ":\n" + throwableDescription);

    if (this._settings.printStackTraceOnUncaughtExceptions()) {
        if (e instanceof UserError || e instanceof DeveloperError) {
            e.getCause().printStackTrace(System.err);
        } else {
            e.printStackTrace(System.err);
        }
    }
}

From source file:org.codelibs.fess.servlet.Tomcat6ConfigServlet.java

@SuppressWarnings("deprecation")
private void cleanupAllThreads() {
    final Thread[] threads = getThreads();
    final ClassLoader cl = this.getClass().getClassLoader();
    try {/*from   www . j a  v a 2 s  . com*/
        cl.getResource(null);
    } catch (final Exception e) {
    }

    final List<String> jvmThreadGroupList = new ArrayList<String>();
    jvmThreadGroupList.add("system");
    jvmThreadGroupList.add("RMI Runtime");

    // Iterate over the set of threads
    for (final Thread thread : threads) {
        if (thread != null) {
            final ClassLoader ccl = thread.getContextClassLoader();
            if (ccl != null && ccl.equals(cl)) {
                // Don't warn about this thread
                if (thread == Thread.currentThread()) {
                    continue;
                }

                // Don't warn about JVM controlled threads
                final ThreadGroup tg = thread.getThreadGroup();
                if (tg != null && jvmThreadGroupList.contains(tg.getName())) {
                    continue;
                }

                waitThread(thread);
                // Skip threads that have already died
                if (!thread.isAlive()) {
                    continue;
                }

                if (logger.isInfoEnabled()) {
                    logger.info("Interrupting a thread [" + thread.getName() + "]...");
                }
                thread.interrupt();

                waitThread(thread);
                // Skip threads that have already died
                if (!thread.isAlive()) {
                    continue;
                }

                if (logger.isInfoEnabled()) {
                    logger.info("Stopping a thread [" + thread.getName() + "]...");
                }
                thread.stop();
            }
        }
    }

    Field threadLocalsField = null;
    Field inheritableThreadLocalsField = null;
    Field tableField = null;
    try {
        threadLocalsField = Thread.class.getDeclaredField("threadLocals");
        threadLocalsField.setAccessible(true);
        inheritableThreadLocalsField = Thread.class.getDeclaredField("inheritableThreadLocals");
        inheritableThreadLocalsField.setAccessible(true);
        // Make the underlying array of ThreadLoad.ThreadLocalMap.Entry objects
        // accessible
        final Class<?> tlmClass = Class.forName("java.lang.ThreadLocal$ThreadLocalMap");
        tableField = tlmClass.getDeclaredField("table");
        tableField.setAccessible(true);
    } catch (final Exception e) {
        // ignore
    }
    for (final Thread thread : threads) {
        if (thread != null) {

            Object threadLocalMap;
            try {
                // Clear the first map
                threadLocalMap = threadLocalsField.get(thread);
                clearThreadLocalMap(cl, threadLocalMap, tableField);
            } catch (final Exception e) {
                // ignore
            }
            try { // Clear the second map
                threadLocalMap = inheritableThreadLocalsField.get(thread);
                clearThreadLocalMap(cl, threadLocalMap, tableField);
            } catch (final Exception e) {
                // ignore
            }
        }
    }
}

From source file:com.spotify.helios.system.SystemTestBase.java

private void listThreads() {
    final Set<Thread> threads = Thread.getAllStackTraces().keySet();
    final Map<String, Thread> sorted = Maps.newTreeMap();
    for (final Thread t : threads) {
        final ThreadGroup tg = t.getThreadGroup();
        if (t.isAlive() && (tg == null || !tg.getName().equals("system"))) {
            sorted.put(t.getName(), t);/*w  ww .ja  v a 2 s  .  co m*/
        }
    }
    log.info("= THREADS " + Strings.repeat("=", 70));
    for (final Thread t : sorted.values()) {
        final ThreadGroup tg = t.getThreadGroup();
        log.info("{}: \"{}\" ({}{})", t.getId(), t.getName(), (tg == null ? "" : tg.getName() + " "),
                (t.isDaemon() ? "daemon" : ""));
    }
    log.info(Strings.repeat("=", 80));
}

From source file:org.jumpmind.symmetric.AbstractSymmetricEngine.java

public synchronized void stop() {

    log.info("Stopping SymmetricDS externalId={} version={} database={}",
            new Object[] { parameterService == null ? "?" : parameterService.getExternalId(), Version.version(),
                    symmetricDialect == null ? "?" : symmetricDialect.getName() });
    if (jobManager != null) {
        jobManager.stopJobs();/*w ww .j  av  a2 s .  co  m*/
    }
    if (routerService != null) {
        routerService.stop();
    }
    if (nodeCommunicationService != null) {
        nodeCommunicationService.stop();
    }

    if (pushService != null) {
        pushService.stop();
    }

    if (dataLoaderService != null) {
        dataLoaderService.stop();
    }

    if (statisticManager != null) {
        List<ProcessInfo> infos = statisticManager.getProcessInfos();
        for (ProcessInfo processInfo : infos) {
            Thread thread = processInfo.getThread();
            if (processInfo.getStatus() != Status.OK && thread.isAlive()) {
                log.info("Trying to interrupt thread '{}' ", thread.getName());
                try {
                    thread.interrupt();
                } catch (Exception e) {
                    log.info("Caught exception while attempting to interrupt thread", e);
                }
            }
        }

        Thread.interrupted();
    }

    started = false;
    starting = false;

}