使用ConcurrentLinkedQueue惨痛的教训
服务端原本有个定时任务对一个集合ArrayList 中的消息做处理。 因为考虑到处理消息是先进先出原则,所以优化的时候考虑改用ConcurrentLinkedQueue 当时没仔细深入研究过这个集合就匆匆上线了。结果刚上线第二天就出问题了。服务端一次优化演变成了一个缺陷,还好及时回退了版本,后果才不是很严重。
回退后对ConcurrentLinkedQueue 做了一个简单的测试代码如下:
- import java.util.concurrent.ConcurrentLinkedQueue;
- import java.util.concurrent.CountDownLatch;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- public class ConcurrentLinkedQueueTest {
- private static ConcurrentLinkedQueue<Integer> queue = new ConcurrentLinkedQueue<Integer>();
- private static int count = 100000;
- private static int count2 = 2; // 线程个数
- private static CountDownLatch cd = new CountDownLatch(count2);
- public static void dothis() {
- for (int i = 0; i < count; i++) {
- queue.offer(i);
- }
- }
- public static void main(String[] args) throws InterruptedException {
- long timeStart = System.currentTimeMillis();
- ExecutorService es = Executors.newFixedThreadPool(4);
- ConcurrentLinkedQueueTest.dothis();
- for (int i = 0; i < count2; i++) {
- es.submit(new Poll());
- }
- cd.await();
- System.out.println("cost time "
- + (System.currentTimeMillis() - timeStart) + "ms");
- es.shutdown();
- }
- static class Poll implements Runnable {
- @Override
- public void run() {
- // while (queue.size()>0) {
- while (!queue.isEmpty()) {
- System.out.println(queue.poll());
- }
- cd.countDown();
- }
- }
- }
运行结果:
costtime 2360ms
改用while (queue.size()>0)后
运行结果:
cost time 46422ms
结果居然相差那么大,看了下ConcurrentLinkedQueue的API 原来.size() 是要遍历一遍集合的,难怪那么慢,所以尽量要避免用size而改用isEmpty().
总结了下, 在单位缺乏性能测试下,对自己的编程要求更加要严格,特别是在生产环境下更是要小心谨慎。
分类:
android提高篇
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
2016-10-17 用UILocalNotification实现一个闹钟(Swift)
2016-10-17 如何在 iOS 8 中使用 Swift 实现本地通知(上)
2016-10-17 如何在 iOS 8 中使用 Swift 实现本地通知(下)
2016-10-17 Swift - 本地消息的推送通知(附样例)
2016-10-17 Swift 本地推送通知UILocalNotification
2014-10-17 Android原理揭秘系列之一动态墙纸