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

余生颓废 提交于 2020-05-28 18:04:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!