150

I have a fixed thread pool that I submit tasks to (limited to 5 threads). How can I find out which one of those 5 threads executes my task (something like "thread #3 of 5 is doing this task")?

ExecutorService taskExecutor = Executors.newFixedThreadPool(5);

//in infinite loop:
taskExecutor.execute(new MyTask());
....

private class MyTask implements Runnable {
    public void run() {
        logger.debug("Thread # XXX is doing this task");//how to get thread id?
    }
}
Mridang Agarwalla
  • 43,201
  • 71
  • 221
  • 382
serg
  • 109,619
  • 77
  • 317
  • 330

6 Answers6

256

Using Thread.currentThread():

private class MyTask implements Runnable {
    public void run() {
        long threadId = Thread.currentThread().getId();
        logger.debug("Thread # " + threadId + " is doing this task");
    }
}
skaffman
  • 398,947
  • 96
  • 818
  • 769
  • 3
    this is actually not the desired answer; one should use `% numThreads` instead – petrbel Nov 06 '14 at 10:00
  • 2
    @petrbel He's answering the question title perfectly, and the thread id is close enough in my opinion when the OP requests "something like 'thread #3 of 5". – CorayThan Sep 01 '15 at 19:20
  • 3
    Note, an example output of `getId()` is `14291` where as `getName()` gives you `pool-29-thread-7`, which I would argue is more useful. – Joshua Pinter Oct 16 '19 at 20:35
26

The accepted answer answers the question about getting a thread id, but it doesn't let you do "Thread X of Y" messages. Thread ids are unique across threads but don't necessarily start from 0 or 1.

Here is an example matching the question:

import java.util.concurrent.*;
class ThreadIdTest {

  public static void main(String[] args) {

    final int numThreads = 5;
    ExecutorService exec = Executors.newFixedThreadPool(numThreads);

    for (int i=0; i<10; i++) {
      exec.execute(new Runnable() {
        public void run() {
          long threadId = Thread.currentThread().getId();
          System.out.println("I am thread " + threadId + " of " + numThreads);
        }
      });
    }

    exec.shutdown();
  }
}

and the output:

burhan@orion:/dev/shm$ javac ThreadIdTest.java && java ThreadIdTest
I am thread 8 of 5
I am thread 9 of 5
I am thread 10 of 5
I am thread 8 of 5
I am thread 9 of 5
I am thread 11 of 5
I am thread 8 of 5
I am thread 9 of 5
I am thread 10 of 5
I am thread 12 of 5

A slight tweak using modulo arithmetic will allow you to do "thread X of Y" correctly:

// modulo gives zero-based results hence the +1
long threadId = Thread.currentThread().getId()%numThreads +1;

New results:

burhan@orion:/dev/shm$ javac ThreadIdTest.java && java ThreadIdTest  
I am thread 2 of 5 
I am thread 3 of 5 
I am thread 3 of 5 
I am thread 3 of 5 
I am thread 5 of 5 
I am thread 1 of 5 
I am thread 4 of 5 
I am thread 1 of 5 
I am thread 2 of 5 
I am thread 3 of 5 
Burhan Ali
  • 2,258
  • 1
  • 28
  • 38
  • 9
    Are Java thread IDs guaranteed to be contiguous? If not, your modulo won't work correctly. – Rag Sep 19 '15 at 00:34
  • @BrianGordon Not sure about a guarantee, but the code seems to nothing more than incrementing an internal counter: http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/lang/Thread.java#l217 – Burhan Ali Sep 19 '15 at 00:44
  • 11
    So if two thread pools were initialized simultaneously, the threads in one of those thread pools might have IDs of, for example, 1, 4, 5, 6, 7 and in that case you would have two different threads with the same "I am thread n of 5" message. – Rag Sep 19 '15 at 00:57
  • @BrianGordon Thread.nextThreadID() is synchronized, so this wouldn't be a problem, right? – Matheus Azevedo May 13 '16 at 03:44
  • 1
    @MatheusAzevedo That has nothing to do with it. – Rag May 13 '16 at 18:58
6

You can use Thread.getCurrentThread.getId(), but why would you want to do that when LogRecord objects managed by the logger already have the thread Id. I think you are missing a configuration somewhere that logs the thread Ids for your log messages.

Vineet Reynolds
  • 76,006
  • 17
  • 150
  • 174
3

If you are using logging then thread names will be helpful. A thread factory helps with this:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

public class Main {

    static Logger LOG = LoggerFactory.getLogger(Main.class);

    static class MyTask implements Runnable {
        public void run() {
            LOG.info("A pool thread is doing this task");
        }
    }

    public static void main(String[] args) {
        ExecutorService taskExecutor = Executors.newFixedThreadPool(5, new MyThreadFactory());
        taskExecutor.execute(new MyTask());
        taskExecutor.shutdown();
    }
}

class MyThreadFactory implements ThreadFactory {
    private int counter;
    public Thread newThread(Runnable r) {
        return new Thread(r, "My thread # " + counter++);
    }
}

Output:

[   My thread # 0] Main         INFO  A pool thread is doing this task
Vitaliy Polchuk
  • 1,878
  • 19
  • 12
1

If your class inherits from Thread, you can use methods getName and setName to name each thread. Otherwise you could just add a name field to MyTask, and initialize it in your constructor.

Justin Ethier
  • 131,333
  • 52
  • 229
  • 284
1

There is the way of current thread getting:

Thread t = Thread.currentThread();

After you have got Thread class object (t) you are able to get information you need using Thread class methods.

Thread ID gettting:

long tId = t.getId(); // e.g. 14291

Thread name gettting:

String tName = t.getName(); // e.g. "pool-29-thread-7"
Joshua Pinter
  • 45,245
  • 23
  • 243
  • 245