Sina Madani
Sina Madani

Reputation: 1324

How to get the number of threads executing current method?

I'm trying to debug performance issues in multithreaded code and I'm wondering if there's a way to print out the number of threads currently executing the method. For example, suppose I have the following:

public void concurrentMethod(Object data) {
    int numberOfThreadsExecutingThisMethodSimulataneously = //...?
    System.out.println(numberOfThreadsExecutingThisMethodSimulataneously);
    //method body...
}

Specifically, I am using a ThreadPoolExecutor, so jobs are being submitted as follows:

ExecutorService executor;
for (Object data : myData) {
    executor.execute(() -> concurrentMethod(data));
}

Upvotes: 0

Views: 80

Answers (1)

Adam Siemion
Adam Siemion

Reputation: 16039

How about

static AtomicInteger currentNumberOfThreads = new AtomicInteger();
public void concurrentMethod(Object data) {
  currentNumberOfThreads.incrementAndGet();
  try {
    // currentNumberOfThreads.gets() 
  } finally {
    currentNumberOfThreads.decrementAndGet();
  }
}

Upvotes: 1

Related Questions