0

在下面的场景中,Java async-profiler 是否是在比较 ArrayBlockingQueue 和 LinkedBlockingQueue 的性能时查看时间花费的正确工具?

在我的机器上,当消费者和生产者之间共享 50M 条目时,ABQ 的总执行时间总是比 LBQ 快 25%。两者的火焰图“几乎”相同,除了 LBQ 仅显示少数来自 JVM 对象分配代码的样本,但这并不能证明 25% 的增长是合理的。正如预期的那样,LBQ 中的 TLAB 分配要高得多。

我想知道,我怎样才能看到哪个活动(无论是代码还是硬件)正在花费时间?

亚军:

import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class Runner {

    public static void main(String[] args) throws InterruptedException {


        int size = 50_000_000;
        BlockingQueue<Long> queue = new LinkedBlockingQueue<>(size);

        Producer producer = new Producer(queue, size);
        Thread t = new Thread(producer);
        t.setName("ProducerItIs");

        Consumer consumer = new Consumer(queue, size);
        Thread t2 = new Thread(consumer);
        t2.setName("ConsumerItIs");


        t.start();
        t2.start();

        Thread.sleep(8000);
        System.out.println("done");
        queue.forEach(System.out::println);
        System.out.println(queue.size());
    }
}

制片人:

import java.util.Queue;
import java.util.Random;
import java.util.concurrent.BlockingQueue;

public class Producer implements Runnable {

    public Producer(BlockingQueue<Long> blockingQueue, int size) {
        this.queue = blockingQueue;
        this.size = size;

    }

    private final BlockingQueue<Long> queue;
    private final int size;

    public void run() {

        System.out.println("Started to produce...");
        long nanos = System.nanoTime();
        Long ii = (long) new Random().nextInt();

        for (int j = 0; j < size; j++) {
                queue.add(ii);
        }
        System.out.println("producer Time taken :" + ((System.nanoTime() - nanos) / 1e6));
    }
}

消费者:

import java.util.concurrent.BlockingQueue;

public class Consumer implements Runnable {

    private final BlockingQueue<Long> blockingQueue;
    private final int size;


    private Long value;

    public Consumer(BlockingQueue<Long> blockingQueue, int size) {
        this.blockingQueue = blockingQueue;
        this.size = size;
    }

    public void run() {
        long nanos = System.nanoTime();

        System.out.println("Starting to consume...");
        int i = 1;
        try {
            while (true) {
                value = blockingQueue.take();
                i++;

                if (i >= size) {
                    break;
                }

            }
            System.out.println("Consumer Time taken :" + ((System.nanoTime() - nanos)/1e6));
        } catch (Exception exp) {
            System.out.println(exp);
        }
    }
    public long getValue() {
        return value;
    }
}

使用 ArrayBlockingQueue: 在此处输入图像描述

使用 LinkedListBlockedQueue:黑色箭头显示为分配捕获的样本 在此处输入图像描述

4

0 回答 0