问题
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
回答1:
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
回答2:
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
.
来源:https://stackoverflow.com/questions/47795282/how-can-i-measure-how-many-threads-are-executing-a-piece-of-code