java.util.concurrent.LinkedBlockingQueue中的奇怪代码 [英] Strange code in java.util.concurrent.LinkedBlockingQueue

查看:342
本文介绍了java.util.concurrent.LinkedBlockingQueue中的奇怪代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

全部!

我在LinkedBlockingQueue中发现了奇怪的代码:

I found strange code in LinkedBlockingQueue:

private E dequeue() {
        // assert takeLock.isHeldByCurrentThread();
        Node<E> h = head;
        Node<E> first = h.next;
        h.next = h; // help GC
        head = first;
        E x = first.item;
        first.item = null;
        return x;
}

谁能解释为什么我们需要局部变量h?它如何对GC有所帮助?

Who can explain why do we need local variable h? How can it help for GC?

推荐答案

为了更好地理解发生了什么,让我们看看执行代码后列表的样子。首先考虑一个初始列表:

To better understand what happens let's see how the list looks like after executing the code. First consider an initial list:

1 -> 2 -> 3

然后 h 指向首先 h.next

1 -> 2 -> 3
|    |
h    first

然后 h.next 指向 h 指向首先

1 -> 2 -> 3
|   / \
h head first

现在,实际上我们知道只有活动参考指向到第一个元素,它本身( h.next = h ),我们也知道GC收集没有更多活动引用的对象,所以当方法结束时,GC可以安全地收集列表的(旧)头部,因为 h 仅存在于方法的范围内。

Now, practically we know that there is only active reference pointing to the first element, which is by itself (h.next = h), and we also know that the GC collects objects that have no more active references, so when the method ends, the (old) head of the list ca be safely collected by the GC since h exists only within the scope of the method.

话虽如此,有人指出,我同意这一点,即使使用经典的出列方法(即只需将第一指向 head.next 指向首先)没有更多指向旧头的参考文献。但是,在这种情况下,旧的头部悬挂在内存中,并且仍然有 next 字段指向第一个,而在您发布的代码中,唯一剩下的就是指向自身的孤立对象。这可能会触发GC更快地采取行动。

Having said this, it was pointed out, and I agree with this, that even with the classic dequeue method (i.e. just make first point to head.next and head point to first) there are no more references pointing towards the old head. However, in this scenario, the old head is left dangling in memory and still has its next field pointing towards first, whereas in the code you posted, the only thing left is an isolated object pointing to itself. This may be triggering the GC to act faster.

这篇关于java.util.concurrent.LinkedBlockingQueue中的奇怪代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆