Purpose of overloaded constructor in SynchronizedMap class

会有一股神秘感。 提交于 2019-12-23 02:22:00

问题


In Collections class, class SynchronizedMap has two constructors. One takes only a map instance and another with a map and a mutex.

    SynchronizedMap(Map<K,V> m) {
        this.m = Objects.requireNonNull(m);
        mutex = this;
    }

    SynchronizedMap(Map<K,V> m, Object mutex) {
        this.m = m;
        this.mutex = mutex;
    }

However, SynchronizedMap class is a private static class and only way to access it using provided wrapper method:

public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m) {
    return new SynchronizedMap<>(m);
}

As understood from this link, the idea of the second constructor to use user-supplied mutex other than this. Now, since the wrapper method is the only way to get an instance of SynchronizedMap (which takes only a map object) , what is the purpose of this second overloaded constructor?


回答1:


It is used e.g. in SynchronizedSortedMap which extends SynchronizedMap when creating submap view.

 public SortedMap<K,V> subMap(K fromKey, K toKey) {
            synchronized (mutex) {
                return new SynchronizedSortedMap<>(
                    sm.subMap(fromKey, toKey), mutex);
            }
        }

To share the same mutex.



来源:https://stackoverflow.com/questions/50829463/purpose-of-overloaded-constructor-in-synchronizedmap-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!