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:srvmonitor.thKeepAliveServices.java

@Override
public void run() {
    Thread tr = Thread.currentThread();
    System.out.println("Current Thread KeepAlive: " + tr.getName() + " ID: " + tr.getId());

    Timer timerMain = new Timer("thSubKeep");
    timerMain.schedule(new mainKeepTask(), 1000, 10000);
}

From source file:net.bull.javamelody.internal.model.JavaInformations.java

public static List<ThreadInformations> buildThreadInformationsList() {
    final ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
    final Map<Thread, StackTraceElement[]> stackTraces = Thread.getAllStackTraces();
    final List<Thread> threads = new ArrayList<Thread>(stackTraces.keySet());

    // si "1.6.0_01".compareTo(Parameters.JAVA_VERSION) > 0;
    // on rcuprait les threads sans stack trace en contournant bug 6434648 avant 1.6.0_01
    // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6434648
    // hormis pour le thread courant qui obtient sa stack trace diffremment sans le bug
    //      threads = getThreadsFromThreadGroups();
    //      final Thread currentThread = Thread.currentThread();
    //      stackTraces = Collections.singletonMap(currentThread, currentThread.getStackTrace());

    final boolean cpuTimeEnabled = threadBean.isThreadCpuTimeSupported() && threadBean.isThreadCpuTimeEnabled();
    final long[] deadlockedThreads = getDeadlockedThreads(threadBean);
    final List<ThreadInformations> threadInfosList = new ArrayList<ThreadInformations>(threads.size());
    // hostAddress rcupr ici car il peut y avoir plus de 20000 threads
    final String hostAddress = Parameters.getHostAddress();
    for (final Thread thread : threads) {
        final StackTraceElement[] stackTraceElements = stackTraces.get(thread);
        final List<StackTraceElement> stackTraceElementList = stackTraceElements == null ? null
                : new ArrayList<StackTraceElement>(Arrays.asList(stackTraceElements));
        final long cpuTimeMillis;
        final long userTimeMillis;
        if (cpuTimeEnabled) {
            cpuTimeMillis = threadBean.getThreadCpuTime(thread.getId()) / 1000000;
            userTimeMillis = threadBean.getThreadUserTime(thread.getId()) / 1000000;
        } else {/* w  w  w.j  av a2s  .c om*/
            cpuTimeMillis = -1;
            userTimeMillis = -1;
        }
        final boolean deadlocked = deadlockedThreads != null
                && Arrays.binarySearch(deadlockedThreads, thread.getId()) >= 0;
        // stackTraceElementList est une ArrayList et non unmodifiableList pour lisibilit xml
        threadInfosList.add(new ThreadInformations(thread, stackTraceElementList, cpuTimeMillis, userTimeMillis,
                deadlocked, hostAddress));
    }
    // on retourne ArrayList et non unmodifiableList pour lisibilit du xml par xstream
    return threadInfosList;
}

From source file:voltkvqa.AsyncBenchmark.java

/**
 * Fake an internal jstack to the log/*from   www . ja  va 2 s .  c om*/
 */
static public void printJStack() {
    prt(new Date().toString() + " Full thread dump");

    Map<String, List<String>> deduped = new HashMap<String, List<String>>();

    // collect all the output, but dedup the identical stack traces
    for (Entry<Thread, StackTraceElement[]> e : Thread.getAllStackTraces().entrySet()) {
        Thread t = e.getKey();
        String header = String.format("\"%s\" %sprio=%d tid=%d %s", t.getName(), t.isDaemon() ? "daemon " : "",
                t.getPriority(), t.getId(), t.getState().toString());

        String stack = "";
        for (StackTraceElement ste : e.getValue()) {
            stack += "    at " + ste.toString() + "\n";
        }

        if (deduped.containsKey(stack)) {
            deduped.get(stack).add(header);
        } else {
            ArrayList<String> headers = new ArrayList<String>();
            headers.add(header);
            deduped.put(stack, headers);
        }
    }

    for (Entry<String, List<String>> e : deduped.entrySet()) {
        String logline = "";
        for (String header : e.getValue()) {
            logline += header + "\n";
        }
        logline += e.getKey();
        prt(logline);
    }
}

From source file:bear.core.BearMain.java

public static StringBuilder threadDump() {
    Map<Thread, StackTraceElement[]> map = Thread.getAllStackTraces();

    StringBuilder sb = new StringBuilder();

    for (Map.Entry<Thread, StackTraceElement[]> e : map.entrySet()) {
        Thread thread = e.getKey();

        StackTraceElement[] elements = e.getValue();
        StackTraceElement el = elements == null || elements.length == 0 ? null : elements[0];

        sb.append(thread.getName());/*from  ww w.  j a  v a  2  s.c o  m*/
        if (el != null) {
            sb.append("\tat ").append(el).append("\n");
        }
    }

    sb.append("\n\n");

    Exception e = new Exception();

    for (Map.Entry<Thread, StackTraceElement[]> entry : map.entrySet()) {
        Thread thread = entry.getKey();
        StackTraceElement[] stack = entry.getValue();
        sb.append(thread.getName()).append(", id=").append(thread.getId()).append("\n");
        e.setStackTrace(stack);
        sb.append(Throwables.getStackTraceAsString(e));
        sb.append("\n");
    }

    return sb;
}

From source file:com.baidu.fsg.uid.utils.NamingThreadFactory.java

@Override
public Thread newThread(Runnable r) {
    Thread thread = new Thread(r);
    thread.setDaemon(this.daemon);

    // If there is no specified name for thread, it will auto detect using the invoker classname instead.
    // Notice that auto detect may cause some performance overhead
    String prefix = this.name;
    if (StringUtils.isBlank(prefix)) {
        prefix = getInvoker(2);/*from w  w  w  .  j a va  2  s  .  co m*/
    }
    thread.setName(prefix + "-" + getSequence(prefix));

    // no specified uncaughtExceptionHandler, just do logging.
    if (this.uncaughtExceptionHandler != null) {
        thread.setUncaughtExceptionHandler(this.uncaughtExceptionHandler);
    } else {
        thread.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
            public void uncaughtException(Thread t, Throwable e) {
                LOGGER.error("unhandled exception in thread: " + t.getId() + ":" + t.getName(), e);
            }
        });
    }

    return thread;
}

From source file:com.github.hrpc.rpc.RPCCallBenchmark.java

private long getTotalCpuTime(Iterable<? extends Thread> threads) {
    long total = 0;
    for (Thread t : threads) {
        long tid = t.getId();
        total += threadBean.getThreadCpuTime(tid);
    }// w  w  w  .j a  v a2  s. c  om
    return total;
}

From source file:jetbrains.exodus.env.StuckTransactionMonitor.java

@Override
protected void execute() throws Throwable {
    if (env.isOpen()) {
        try {/*www. j  a  v  a  2 s  .co m*/
            final TransactionImpl oldestTxn = env.getOldestTransaction();
            if (oldestTxn == null) {
                return;
            }
            final long created = oldestTxn.getCreated();
            if (created + env.getEnvironmentConfig().getEnvMonitorTxnsTimeout() < System.currentTimeMillis()) {
                final Thread creatingThread = oldestTxn.getCreatingThread();
                logging.error("Transaction timed out: created at " + new Date(created).toString()
                        + ", thread = " + creatingThread + '('
                        + (creatingThread == null ? "" : creatingThread.getId()) + ')', oldestTxn.getTrace());
            }
        } finally {
            queueThis();
        }
    }
}

From source file:com.hurence.logisland.engine.SparkRecordStreamProcessingTest.java

@Before
public void setUp() throws InterruptedException, IOException {
    kafkaContext = new EmbeddedKafkaEnvironment();
    Properties properties = TestUtils.getProducerConfig("localhost:" + kafkaContext.getBrokerPort());
    ProducerConfig producerConfig = new ProducerConfig(properties);
    producer = new Producer(producerConfig);
    kafkaContext.getKafkaUnitServer().createTopic(AbstractKafkaRecordStream.DEFAULT_ERRORS_TOPIC().getValue());
    kafkaContext.getKafkaUnitServer().createTopic(AbstractKafkaRecordStream.DEFAULT_EVENTS_TOPIC().getValue());
    kafkaContext.getKafkaUnitServer().createTopic(AbstractKafkaRecordStream.DEFAULT_RAW_TOPIC().getValue());
    kafkaContext.getKafkaUnitServer().createTopic(AbstractKafkaRecordStream.DEFAULT_METRICS_TOPIC().getValue());

    // deleting zookeeper information to make sure the consumer starts from the beginning
    // see https://stackoverflow.com/questions/14935755/how-to-get-data-from-old-offset-point-in-kafka
    assertTrue(kafkaContext.getZkClient() != null);
    ZkClient zkClient = kafkaContext.getZkClient();
    zkClient.delete("/consumers/group0");

    // setup simple consumer
    Properties consumerProperties = TestUtils.createConsumerProperties(kafkaContext.getZkConnect(), "group0",
            "consumer0", 3000);
    consumer = Consumer.createJavaConsumerConnector(new ConsumerConfig(consumerProperties));
    engineConfiguration = createEngineConfiguration();

    /*/*from  w  ww.j a  va2 s .c  om*/
            File checkpointDir = new File("checkpoints");
            if (checkpointDir.isDirectory())
    FileUtils.forceDelete(checkpointDir);*/

    Optional<EngineContext> instance = ComponentFactory.getEngineContext(engineConfiguration);
    assertTrue(instance.isPresent());
    assertTrue(instance.get().isValid());
    ProcessingEngine engine = instance.get().getEngine();
    EngineContext engineContext = instance.get();

    Thread.sleep(2000);
    Runnable myRunnable = new Runnable() {
        @Override
        public void run() {
            System.setProperty("hadoop.home.dir", "/");
            engine.start(engineContext);
            engine.shutdown(engineContext);
            System.out.println("done");
        }
    };
    Thread t = new Thread(myRunnable);
    logger.info("starting engine thread {}", t.getId());
    t.start();

    Thread.sleep(6000);
    logger.info("done waiting for engine startup");
}

From source file:metlos.executors.batch.BatchCpuThrottlingExecutorTest.java

@Test
public void maxUsage_SingleThreaded() throws Exception {
    NamingThreadFactory factory = new NamingThreadFactory();
    ThreadPoolExecutor e = new ThreadPoolExecutor(1, 1, 0, TimeUnit.DAYS, new LinkedBlockingQueue<Runnable>(),
            factory);//from  w w  w  . j a va2s.c o m
    e.prestartAllCoreThreads();

    List<Future<?>> payloadResults = new ArrayList<Future<?>>();

    long startTime = System.nanoTime();

    //create load
    for (int i = 0; i < NOF_JOBS; ++i) {
        Future<?> f = e.submit(new Payload());
        payloadResults.add(f);
    }

    //wait for it all to finish
    for (Future<?> f : payloadResults) {
        f.get();
    }

    long endTime = System.nanoTime();

    long time = endTime - startTime;
    LOG.info("MAX Singlethreaded test took " + (time / 1000.0 / 1000.0) + "ms");

    ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
    long cpuTime = 0;
    for (Thread t : factory.createdThreads) {
        long threadCpuTime = threadBean.getThreadCpuTime(t.getId());
        LOG.info(t.getName() + ": " + threadCpuTime + "ns");
        cpuTime += threadCpuTime;
    }

    float actualUsage = (float) cpuTime / time;

    LOG.info("MAX Singlethreaded overall usage: " + actualUsage);
}

From source file:metlos.executors.batch.BatchCpuThrottlingExecutorTest.java

@Test
public void maxUsage_MultiThreaded() throws Exception {
    NamingThreadFactory factory = new NamingThreadFactory();
    ThreadPoolExecutor e = new ThreadPoolExecutor(10, 10, 0, TimeUnit.DAYS, new LinkedBlockingQueue<Runnable>(),
            factory);/*from w  w  w.  j  a  va 2s  .c o  m*/
    e.prestartAllCoreThreads();

    List<Future<?>> payloadResults = new ArrayList<Future<?>>();

    long startTime = System.nanoTime();

    //create load
    for (int i = 0; i < NOF_JOBS; ++i) {
        Future<?> f = e.submit(new Payload());
        payloadResults.add(f);
    }

    //wait for it all to finish
    for (Future<?> f : payloadResults) {
        f.get();
    }

    long endTime = System.nanoTime();

    long time = endTime - startTime;
    LOG.info("MAX Multithreaded test took " + (time / 1000.0 / 1000.0) + "ms");

    ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
    long cpuTime = 0;
    for (Thread t : factory.createdThreads) {
        long threadCpuTime = threadBean.getThreadCpuTime(t.getId());
        LOG.info(t.getName() + ": " + threadCpuTime + "ns");
        cpuTime += threadCpuTime;
    }

    float actualUsage = (float) cpuTime / time;

    LOG.info("MAX Multithreaded overall usage: " + actualUsage);
}