问题描述
在集合
类中,类 SynchronizedMap
有两个构造函数。一个只需要一个 map
实例,另一个带有 map
和一个 mutex
。
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;
}
但是,SynchronizedMap类是一个私有静态类,只能使用它来访问它提供的包装方法:
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);
}
从,第二个构造函数使用用户提供的互斥锁的想法
除了此
。现在,因为包装器方法是获取 SynchronizedMap
实例的唯一方法(它只接受一个map对象),所以第二个重载构造函数的目的是什么?
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?
推荐答案
用于例如在 SynchronizedSortedMap
中,在创建子图视图时扩展 SynchronizedMap
。
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);
}
}
共享相同的互斥锁。
这篇关于SynchronizedMap类中重载构造函数的用途的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!