造轮子之MemorySafeLinkedBlockingQueue
造輪子之MemorySafeLinkedBlockingQueue-LinkBlockingQueue改進(jìn)
LinkBlockingQueue改進(jìn)
問(wèn)題背景
https://github.com/apache/dubbo/pull/9722/files
使用線程池的同學(xué)對(duì)于標(biāo)題中的隊(duì)列想必都有過(guò)使用,但上述隊(duì)列使用不當(dāng)時(shí)則會(huì)造成程序OOM ,那怎么來(lái)控制呢?
使用ArrayBlockingQueue ?如何來(lái)評(píng)估長(zhǎng)度 ?
是否有一個(gè)完美的解決方案呢,MemorySafeLinkedBlockingQueue則通過(guò)對(duì)內(nèi)存的限制判斷盡面控制隊(duì)列的容量 ,完成解決了可能存在的OOM問(wèn)題。
獲取內(nèi)存大?。ㄗ?:?jiǎn)挝淮驜;支持準(zhǔn)實(shí)時(shí)更新):
Runtime.getRuntime().freeMemory()//JVM中已經(jīng)申請(qǐng)到的堆內(nèi)存中還未使用的大小Runtime.getRuntime().maxMemory()// JVM可從操作系統(tǒng)申請(qǐng)到的最大內(nèi)存值 -XxmRuntime.getRuntime().totalMemory()// JVM已從操作系統(tǒng)申請(qǐng)到的內(nèi)存大小 —Xxs可設(shè)置該值大小-初始堆的大小線程池在excute任務(wù)時(shí) ,放隊(duì)列 ,放不進(jìn)去,使用新線程運(yùn)行任務(wù)。這個(gè)放不進(jìn)行 ,是使用的offer??非阻塞方法嗎?
參考:https://blog.csdn.net/weixin_43108539/article/details/125190023
public void execute(Runnable command) { if (command == null) throw new NullPointerException(); //拿到32位的int int c = ctl.get(); //工作線程數(shù)<核心線程數(shù) if (workerCountOf(c) < corePoolSize) { //進(jìn)入if,代表可以創(chuàng)建 核心 線程數(shù) if (addWorker(command, true)) return; //如果沒(méi)進(jìn)入if
,代表創(chuàng)建核心線程數(shù)失敗,重新獲取 ctl c = ctl.get(); } //判斷線程池為Running狀態(tài)