并发组件中的size()方法导致cpu狂飙

import java.util.Date;
import java.util.concurrent.ConcurrentLinkedQueue;

public class AsyncEventSender {

	private static final long MAX_BUFFER_SIZE = 10000000;
	
	private ConcurrentLinkedQueue<String> bufferQueue = new ConcurrentLinkedQueue<String>();
	
	public void sendEventAsync(String event){
		int size = bufferQueue.size();
		if(size < MAX_BUFFER_SIZE){
			bufferQueue.add(event);
		}
	}
	
	public static void main(String[] args){
		AsyncEventSender sender = new AsyncEventSender();
		long start = new Date().getTime();
		for(int i=0;i<1000000;i++){
			if(i % 5000 == 0){
				System.out.println(i+"XXXX"+(new Date().getTime()-start));
				start = new Date().getTime();
			}
			sender.sendEventAsync(i+"");
		}
	}
}

随着队列中元素的不断增加,size()方法越来越耗时,长期占用cpu,导致负载狂飙。

Concurrent系列的集合类使用分桶的策略减少集合的线程竞争,在获取其整体大小时需要进行统计,而不是直接返回一个预先存储的值,获取的时间复杂度是o(n)。随着元素增加越来越多,统计越来越慢。

发布了177 篇原创文章 · 获赞 14 · 访问量 47万+

猜你喜欢

转载自blog.csdn.net/qian_348840260/article/details/80763367