java compareandset 包_在Java中,AtomicInteger compareAndSet()和synced关键字的性能如何?...
我實(shí)現(xiàn)了請求實(shí)例的FIFO隊(duì)列(為速度預(yù)先分配了請求對象),并開始在add方法上使用“
synchronized”關(guān)鍵字。該方法很短(檢查是否在固定大小的緩沖區(qū)中有空間,然后將值添加到數(shù)組中)。使用visualVM,似乎線程阻塞的次數(shù)比我喜歡的要多(確切地說,是“監(jiān)視器”)。因此,我將代碼轉(zhuǎn)換為將AtomicInteger值用于諸如跟蹤當(dāng)前大小之類的事情,然后在while循環(huán)中使用compareAndSet()(就像AtomicInteger在內(nèi)部對諸如gainAndGet()之類的方法一樣)。該代碼現(xiàn)在看起來更長了。
我想知道的是,使用同步和較短的代碼與不使用synced關(guān)鍵字的較長的代碼(因此永遠(yuǎn)不要在鎖上阻塞)的性能開銷是多少?
這是帶有synced關(guān)鍵字的舊get方法:
public synchronized Request get()
{
if (head == tail)
{
return null;
}
Request r = requests[head];
head = (head + 1) % requests.length;
return r;
}
這是不帶有synced關(guān)鍵字的新get方法:
public Request get()
{
while (true)
{
int current = size.get();
if (current <= 0)
{
return null;
}
if (size.compareAndSet(current, current - 1))
{
break;
}
}
while (true)
{
int current = head.get();
int nextHead = (current + 1) % requests.length;
if (head.compareAndSet(current, nextHead))
{
return requests[current];
}
}
}
我的猜測是,由于代碼較短,但由于存在鎖阻塞(可能導(dǎo)致線程上下文切換等)的風(fēng)險(xiǎn),所以synced關(guān)鍵字更糟。
謝謝!
總結(jié)
以上是生活随笔為你收集整理的java compareandset 包_在Java中,AtomicInteger compareAndSet()和synced关键字的性能如何?...的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 买羊奶的店如何运营管理?
- 下一篇: java 返回值void_Java的返回