Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I measure how many threads are executing a piece of code?

I am trying to measure how many threads are executing a section of code at the same time. Currently i am (ab)using Semaphores for this, is there a better way?

final int MAX_THREADS = Integer.MAX_VALUE;

Semaphore s = new Semaphore(MAX_THREADS);

s.acquire(); // start of section

// do some computations

// track how many threads are running the section
trackThreads( (MAX_THREADS - s.availablePermits()) );         

s.release(); // end of section
like image 608
ChrisBlom Avatar asked Dec 13 '17 14:12

ChrisBlom


People also ask

How can I tell how many threads are running?

Open Task Manager (press Ctrl+Shift+Esc) Select Performance tab. Look for Cores and Logical Processors (Threads)

How many threads can a program run?

Each core can only run 1 thread at a time, i.e. hyperthreading is disabled. So, you can have a total maximum of 20 threads executing in parallel, one thread per CPU/core.

How many threads are created by executing the following program?

Answer: 3 : 2 threads are there. Main program is also run as a thread. And, program has created one child thread. Hence, total 2 threads are there in the program.


2 Answers

Use an AtomicInteger instead of a Semaphore.

Something along the lines of :

AtomicInteger count = new AtomicInteger();

count.getAndIncrement();

// do some computations

// track how many threads are running the section
trackThreads( count.get() );         

count.getAndDecrement(); // end of section
like image 176
Henrik Aasted Sørensen Avatar answered Sep 27 '22 18:09

Henrik Aasted Sørensen


AtomicInteger is good suggestion, but since java-8 there is LongAdder that is much better suited in high contended environments.

The difference is that when a CAS fails, AtomicInteger will try again - until it will succeed. A LongAdder when it fails to CAS (there is a spin lock inside), will create an array of the values that "failed" (limited to the number of CPU's if I remember correctly). When the you finally request it's current value - all those "failed" values are added to the result. This strategy proves to be quite faster than AtomicInteger.

like image 43
Eugene Avatar answered Sep 27 '22 18:09

Eugene