The Wayback Machine - https://web.archive.org/web/20201013054124/https://github.com/Snailclimb/JavaGuide/issues/713
Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ConcurrentHashMap中TreeBin与TreeNode的区别 #713

Open
jizhuozhi opened this issue Apr 5, 2020 · 1 comment
Open

ConcurrentHashMap中TreeBin与TreeNode的区别 #713

jizhuozhi opened this issue Apr 5, 2020 · 1 comment

Comments

@jizhuozhi
Copy link

@jizhuozhi jizhuozhi commented Apr 5, 2020

Java集合框架常见面试题.md

在Java1.8的实现中,TreeBin并不是红黑树的存储节点,TreeBin通过root属性维护红黑树的根结点,因为红黑树在旋转的时候,根结点可能会被它原来的子节点替换掉,在这个时间点,如果有其他线程要写这棵红黑树就会发生线程不安全问题,所以在ConcurrentHashMap中TreeBin通过waiter属性维护当前使用这棵红黑树的线程,来防止其他线程的进入。

所以在Java8中TreeBin并没有指向下一节点的引用,而是使用TreeNode来存储红黑树节点

static final class TreeBin<K,V> extends Node<K,V> {
        TreeNode<K,V> root;
        volatile TreeNode<K,V> first;
        volatile Thread waiter;
        volatile int lockState;
        // values for lockState
        static final int WRITER = 1; // set while holding write lock
        static final int WAITER = 2; // set when waiting for write lock
        static final int READER = 4; // increment value for setting read lock
...
}
@Snailclimb
Copy link
Owner

@Snailclimb Snailclimb commented Apr 12, 2020

👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
2 participants
You can’t perform that action at this time.