对于静态内部类 我能想到的只有 获取内部类的实例无需有外部类实例的引用 。被问及到一个问题 ConcurrentHashMap 中HashEntry 为什么被设置为静态内部类。
我感觉应该是为了在发布 HashEntry 的时候不会发布ConcurrentHashMap的this 引用。 但是这样做目的是什么为了并发更安全?
求大神解释
我感觉应该是为了在发布 HashEntry 的时候不会发布ConcurrentHashMap的this 引用。 但是这样做目的是什么为了并发更安全?
求大神解释
//理解有误区,ConcurrentHashMap发布访问时并不是发布静态内部类HashEntry,反而是封装了HashEntry的非
//静态final内部类KeySet Values EntrySet, 这3个类分别封装了KeyIterator ValueIterator
// EntryIterator
//你可以看一看源代码, HashEntry 其实很简单。ConcurrentHashMap并不会直接发布它 他也不是一个
//实现了Map.Entry接口的类什么的。 因为它只是一个工具类辅助ConcurrentHashMap里的final非静态内部类
//KeyIterator ValueIterator EntryIterator,这几个类才是真正被发布的要访问ConcurrentHashMap的非静
//态属性和方法的的内部类。
//所以得出结论,为了更高的内部聚合,访问最严格性,HashEntry既然是一个工具类不需要访问
//ConcurrentHashMap的一些信息,使它的访问域最小就可以用上静态内不类 /**
* ConcurrentHashMap list entry. Note that this is never exported
* out as a user-visible Map.Entry.
*
* Because the value field is volatile, not final, it is legal wrt
* the Java Memory Model for an unsynchronized reader to see null
* instead of initial value when read via a data race. Although a
* reordering leading to this is not likely to ever actually
* occur, the Segment.readValueUnderLock method is used as a
* backup in case a null (pre-initialized) value is ever seen in
* an unsynchronized access method.
*/
static final class HashEntry<K,V> {
final K key;
final int hash;
volatile V value;
final HashEntry<K,V> next; HashEntry(K key, int hash, HashEntry<K,V> next, V value) {
this.key = key;
this.hash = hash;
this.next = next;
this.value = value;
} @SuppressWarnings("unchecked")
static final <K,V> HashEntry<K,V>[] newArray(int i) {
return new HashEntry[i];
}
}
ConcurrentHashMap中HashEntry又是多线程共享的,static更合适。