Example usage for java.lang Thread getId

List of usage examples for java.lang Thread getId

Introduction

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

Prototype

public long getId() 

Source Link

Document

Returns the identifier of this Thread.

Usage

From source file:org.sakaiproject.status.StatusServlet.java

protected void reportThreadDetails(HttpServletResponse response) throws Exception {
    PrintWriter pw = response.getWriter();

    for (Thread thread : findAllThreads()) {
        if (thread != null) {
            String threadLocation = "";
            try {
                StackTraceElement ste = thread.getStackTrace()[0];
                StackTraceElement ste2 = thread.getStackTrace()[1];
                threadLocation = ste.getClassName() + "." + ste.getMethodName() + "()," + ste.getFileName()
                        + ":" + ste.getLineNumber() + "," + ste2.getClassName() + "." + ste2.getMethodName()
                        + "()," + ste2.getFileName() + ":" + ste2.getLineNumber();
            } catch (Exception e) {
                threadLocation = "?,?,?,?";
            }//  ww  w .ja  v a2 s . c  o m
            pw.print(thread.getThreadGroup().getName() + "," + thread.getId() + "," + thread.getName() + ","
                    + thread.getPriority() + "," + thread.getState().name() + ","
                    + (thread.isAlive() ? "" : "notalive") + "," + (thread.isDaemon() ? "daemon" : "") + ","
                    + (thread.isInterrupted() ? "interrupted" : "") + "," + threadLocation + "\n");
        }
    }
}

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 w w. j ava2  s . c  o  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:com.intuit.tank.harness.APITestHarness.java

/**
 * check the agent threads if simulation time has been met.
 *//*from   www  .  j  a v a2 s .  c o  m*/
public void checkAgentThreads() {
    int activeCount = threadGroup.activeCount();
    Thread[] threads = new Thread[activeCount];
    threadGroup.enumerate(threads);
    int activeThreads = 0;
    for (Thread t : threads) {
        if (t != null) {
            if (t.getState() == Thread.State.TIMED_WAITING || t.getState() == Thread.State.WAITING) {
                activeThreads++;
            }
        }
    }
    LOG.info(LogUtil.getLogMessage("Have " + activeThreads + " of " + activeCount
            + " active Threads in thread group " + threadGroup.getName(), LogEventType.System));
    if (agentRunData.getSimulationTime() != 0 && hasMetSimulationTime() && doneSignal.getCount() != 0) {
        boolean exceededTimeLimit = System.currentTimeMillis() > getMaxSimulationEndTimeMillis();
        if (exceededTimeLimit) {
            LOG.info(LogUtil.getLogMessage("Max simulation time has been met and there are "
                    + doneSignal.getCount() + " threads not reporting done."));
            for (Thread t : sessionThreads) {
                if (t.isAlive()) {
                    if (exceededTimeLimit) {
                        LOG.warn(
                                LogUtil.getLogMessage(
                                        "thread " + t.getName() + '-' + t.getId()
                                                + " is still running with a State of " + t.getState().name(),
                                        LogEventType.System));
                        t.interrupt();
                        doneSignal.countDown();
                    }
                }
            }
        }
    }
}

From source file:org.apache.hadoop.hive.metastore.cache.CachedStore.java

@VisibleForTesting
/**/*from ww w.j ava 2s .c o  m*/
 * This starts a background thread, which initially populates the SharedCache and later
 * periodically gets updates from the metastore db
 *
 * @param conf
 * @param runOnlyOnce
 * @param shouldRunPrewarm
 */
static synchronized void startCacheUpdateService(Configuration conf, boolean runOnlyOnce,
        boolean shouldRunPrewarm) {
    if (cacheUpdateMaster == null) {
        initBlackListWhiteList(conf);
        if (!MetastoreConf.getBoolVar(conf, ConfVars.HIVE_IN_TEST)) {
            cacheRefreshPeriodMS = MetastoreConf.getTimeVar(conf,
                    ConfVars.CACHED_RAW_STORE_CACHE_UPDATE_FREQUENCY, TimeUnit.MILLISECONDS);
        }
        LOG.info("CachedStore: starting cache update service (run every {} ms", cacheRefreshPeriodMS);
        cacheUpdateMaster = Executors.newScheduledThreadPool(1, new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                Thread t = Executors.defaultThreadFactory().newThread(r);
                t.setName("CachedStore-CacheUpdateService: Thread-" + t.getId());
                t.setDaemon(true);
                return t;
            }
        });
        if (!runOnlyOnce) {
            cacheUpdateMaster.scheduleAtFixedRate(new CacheUpdateMasterWork(conf, shouldRunPrewarm), 0,
                    cacheRefreshPeriodMS, TimeUnit.MILLISECONDS);
        }
    }
    if (runOnlyOnce) {
        // Some tests control the execution of the background update thread
        cacheUpdateMaster.schedule(new CacheUpdateMasterWork(conf, shouldRunPrewarm), 0, TimeUnit.MILLISECONDS);
    }
}

From source file:com.mirth.connect.donkey.server.channel.Channel.java

/**
 * Start the channel and all of the channel's connectors.
 *//*from   w  w  w .ja v  a 2 s  . c  om*/
public synchronized void start(Set<Integer> connectorsToStart) throws StartException {
    if (currentState == DeployedState.DEPLOYING || currentState == DeployedState.STOPPED) {
        List<Integer> startedMetaDataIds = new ArrayList<Integer>();

        try {
            ThreadUtils.checkInterruptedStatus();

            updateCurrentState(DeployedState.STARTING);

            /*
             * We can't guarantee the state of the process lock when the channel was stopped or
             * halted, so we just reset it.
             */
            processLock.reset();
            removeContentLock = new ReentrantLock(true);
            dispatchThreads.clear();
            shuttingDown = false;
            stopSourceQueue = false;

            // Remove any items in the queue's buffer because they may be outdated and refresh the queue size.
            sourceQueue.invalidate(true, true);

            channelExecutor = Executors.newCachedThreadPool();

            // start the destination connectors but not the destination queues
            for (DestinationChainProvider chainProvider : destinationChainProviders) {
                for (Integer metaDataId : chainProvider.getMetaDataIds()) {
                    DestinationConnector destinationConnector = chainProvider.getDestinationConnectors()
                            .get(metaDataId);

                    if (destinationConnector.getCurrentState() == DeployedState.STOPPED
                            && (connectorsToStart == null || connectorsToStart.contains(metaDataId))) {
                        startedMetaDataIds.add(metaDataId);
                        destinationConnector.start();
                    }
                }
            }

            ThreadUtils.checkInterruptedStatus();
            try {
                processUnfinishedMessages();
            } catch (InterruptedException e) {
                logger.error("Startup recovery interrupted for channel " + name + " (" + channelId + ")", e);
                throw e;
            } catch (Exception e) {
                Throwable cause;
                if (e instanceof ExecutionException) {
                    cause = e.getCause();
                } else {
                    cause = e;
                }

                logger.error("Startup recovery failed for channel " + name + " (" + channelId + "): "
                        + cause.getMessage(), cause);
            }

            ThreadUtils.checkInterruptedStatus();

            // start the destination queues
            for (Integer metaDataId : startedMetaDataIds) {
                getDestinationConnector(metaDataId).startQueue();
            }

            // Remove any items in the queue's buffer because they may be outdated and refresh the queue size.
            sourceQueue.invalidate(true, true);

            // start up the worker thread that will process queued messages
            if (!sourceConnector.isRespondAfterProcessing()) {
                int processingThreads = ((SourceConnectorPropertiesInterface) sourceConnector
                        .getConnectorProperties()).getSourceConnectorProperties().getProcessingThreads();
                queueThreads.clear();
                for (int i = 1; i <= processingThreads; i++) {
                    Thread queueThread = new Thread(Channel.this);
                    queueThread.setName("Source Queue Thread " + i + " on " + name + " (" + channelId + ")");
                    queueThread.start();
                    queueThreads.put(queueThread.getId(), queueThread);
                }
            }

            if (connectorsToStart == null || connectorsToStart.contains(0)) {
                ThreadUtils.checkInterruptedStatus();
                // start up the source connector
                if (sourceConnector.getCurrentState() == DeployedState.STOPPED) {
                    startedMetaDataIds.add(0);
                    sourceConnector.start();
                }

                updateCurrentState(DeployedState.STARTED);
            } else {
                updateCurrentState(DeployedState.PAUSED);
            }
        } catch (Throwable t) {
            if (t instanceof InterruptedException) {
                throw new StartException("Start channel task for " + name + " (" + channelId
                        + ") terminated by halt notification.", t);
            }
            // If an exception occurred, then attempt to rollback by stopping all the connectors that were started
            try {
                updateCurrentState(DeployedState.STOPPING);
                stop(startedMetaDataIds);
                updateCurrentState(DeployedState.STOPPED);
            } catch (Throwable t2) {
                if (t2 instanceof InterruptedException) {
                    throw new StartException("Start channel task for " + name + " (" + channelId
                            + ") terminated by halt notification.", t);
                }

                updateCurrentState(DeployedState.STOPPED);
            }

            throw new StartException("Failed to start channel " + name + " (" + channelId + ").", t);
        }
    } else {
        logger.warn(
                "Failed to start channel " + name + " (" + channelId + "): The channel is already running.");
    }
}

From source file:org.openspaces.admin.internal.admin.DefaultAdmin.java

private ThreadPoolExecutor createThreadPoolExecutor(String threadName, int numberOfThreads,
        final boolean updateSingleThreadId) {
    final ClassLoader correctClassLoader = Thread.currentThread().getContextClassLoader();
    ThreadPoolExecutor executorService = (ThreadPoolExecutor) Executors.newFixedThreadPool(numberOfThreads,
            new GSThreadFactory(threadName, useDaemonThreads) {

                @Override/*from w ww.j av a  2 s.c  o  m*/
                public Thread newThread(Runnable r) {
                    Thread thread = super.newThread(r);
                    thread.setContextClassLoader(correctClassLoader);
                    if (updateSingleThreadId) {
                        DefaultAdmin.this.executorSingleThreadId = thread.getId();
                    }
                    return thread;
                }
            });
    executorService.setRejectedExecutionHandler(DEFAULT_EVENT_LISTENER_REJECTED_POLICY);
    return executorService;
}

From source file:com.android.mms.ui.ComposeMessageActivity.java

@SuppressWarnings("unused")
public static void log(String logMsg) {
    Thread current = Thread.currentThread();
    long tid = current.getId();
    StackTraceElement[] stack = current.getStackTrace();
    String methodName = stack[3].getMethodName();
    // Prepend current thread ID and name of calling method to the message.
    logMsg = "[" + tid + "] [" + methodName + "] " + logMsg;
    Log.d(TAG, logMsg);//from w  w  w .j  a v  a2 s .  com
}

From source file:org.sakaiproject.citation.tool.CitationHelperAction.java

/**
 *
 * @param data/*from   ww w.  j a v a2 s.  co m*/
 */
public void doCancelSearch(RunData data) {
    // get state and params
    SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
    ParameterParser params = data.getParameters();

    int requestStateId = params.getInt("requestStateId", 0);
    restoreRequestState(state,
            new String[] { CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX },
            requestStateId);

    // cancel the running search
    ActiveSearch search = (ActiveSearch) state.getAttribute(STATE_SEARCH_INFO);
    if (search != null) {
        Thread searchThread = search.getSearchThread();
        if (searchThread != null) {
            try {
                searchThread.interrupt();
            } catch (SecurityException se) {
                // not able to interrupt search
                logger.warn("doSearch() [in ThreadGroup " + Thread.currentThread().getThreadGroup().getName()
                        + "] unable to interrupt search Thread [name=" + searchThread.getName() + ", id="
                        + searchThread.getId() + ", group=" + searchThread.getThreadGroup().getName() + "]");
            }
        }
    }

}