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
Open Task Manager (press Ctrl+Shift+Esc) Select Performance tab. Look for Cores and Logical Processors (Threads)
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.
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.
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
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With