0

Once, I've profiled Java application by Async-profiler (CPU utilization). Adnrei Pangin(apangin) thanks for the Async-profiler!

This is stack(hot methods) was at the top:

Started [itimer] profiling
--- Execution profile ---
Total samples       : 6443
unknown_Java        : 17 (0.26%)
not_walkable_Java   : 2 (0.03%)
thread_exit         : 1 (0.02%)

Frame buffer usage  : 42.4103%

--- 1710000000 ns (2.65%), 171 samples
  [ 0] __pthread_cond_timedwait
  [ 1] Unsafe_Park
  [ 2] jdk.internal.misc.Unsafe.park
  [ 3] java.util.concurrent.locks.LockSupport.parkNanos
  [ 4] java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.awaitNanos
  [ 5] java.util.concurrent.ArrayBlockingQueue.poll
  [ 6] xx.Service.run
  [ 7] java.lang.Thread.run

This is Java code which was at the top of CPU-report: xx.Service.class:

public void run() {
    try {
        while (execute) {
            Event event = queue.poll(100, TimeUnit.MILLISECONDS);
            if (event == null) {
                continue;
            }
            do_something();
        }
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
}

"Queue" is ArrayBlockingQueue because it using from different Java threads.

To my mind function __pthread_cond_timedwait shouldn't consume CPU at all because thread was parking without spin loop. But it does this.

Is it normal situation or my code with queue.poll() is incorrect?

Svetlin Zarev
  • 14,713
  • 4
  • 53
  • 82
srg321
  • 105
  • 7
  • 3
    Why poll with only 100 milliseconds? Why not (a lot) longer? You're essentially busy-waiting instead of relying on the blocking queue to wait for you. I'm not 100% sure, but I believe some types of short waits will apply a busy-loop/spinlock type of wait instead of a blocking wait. So choosing a short wait might be a contributing factor. If you're doing this to stop execution early (when `execute` is set to false, consider handling this by adding a 'poison-pill' in the queue to wake it up) – Mark Rotteveel Aug 26 '21 at 11:41
  • 2
    **Waiting** inside `pthread_cond_timedwait` does not consume CPU, but **calling** `pthread_cond_timedwait` does. Parking/unparking (as an operation) is not free. Thread scheduling indeed takes CPU time both on the JVM level and in the OS. – apangin Aug 26 '21 at 12:01
  • hm, essentially CPU using by Thread Context Switching ? – srg321 Aug 26 '21 at 12:18

0 Answers0