OpenJDK's LinkedBlockingQueue implementation:

2019-02-26 08:27发布

This question already has an answer here:

I'm a little confused by the structure of the Node class in OpenJDK's implementation of LinkedBlockingQueue (in java.util.concurrent).

I've reproduced the description of the node class below:

static class Node<E> {
    E item;

    /**
     * One of:
     * - the real successor Node
     * - this Node, meaning the successor is head.next
     * - null, meaning there is no successor (this is the last node)
     */
    Node<E> next;

    Node(E x) { item = x; }
}

Specifically, I'm confused on the 2nd choice for next ("this Node, meaning successor is head.next").

This seems to be directly related to the dequeue method, which looks like:

private E dequeue() {
    // assert takeLock.isHeldByCurrentThread();
    // assert head.item == null;
    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;
}

So we've removed the current head, and we're setting its next to be itself to "help GC".

How does this help GC? How helpful is it to GC?

1条回答
▲ chillily
2楼-- · 2019-02-26 09:16

I asked Professor Doug Lea, author of the code, and he said that it reduces the chances of GC leaving floating garbage.

Some useful resources on floating garbage:

http://www.memorymanagement.org/glossary/f.html#floating.garbage

http://java.sun.com/docs/hotspot/gc1.4.2/#4.4.4.%20Floating%20Garbage|outline

http://blog.johantibell.com/2010/04/generational-garbage-collection-and.html

查看更多
登录 后发表回答