Hashtable 和 Collections.synchronizedMap(HashMap) 的区别 [英] Difference between Hashtable and Collections.synchronizedMap(HashMap)
问题描述
据我所知,java.util.Hashtable
同步 java 中的每个方法.util.Map
接口,而 Collections.synchronizedMap(hash_map)
返回一个包含同步方法的包装对象,将调用委托给实际的hash_map
(如果我错了,请纠正我).
As far as I know, java.util.Hashtable
synchronizes each and every method in the java.util.Map
interface, while Collections.synchronizedMap(hash_map)
returns a wrapper object containing synchronized methods delegating calls to the actual hash_map
(correct me if I am wrong).
我有两个问题:
同步每个方法和拥有一个包装类有什么区别?在哪些情况下可以选择其中一种?
What difference does it make to synchronize each and every method and to have a wrapper class? What are the scenarios to choose one over the other?
当我们执行 Collections.synchronizedMap(hash_table)
时会发生什么?这是否等同于简单地使用一个普通的 java.util.Hashtable
?
What happens when we do Collections.synchronizedMap(hash_table)
? Will this be equal to simply using a normal java.util.Hashtable
?
推荐答案
以下是我从一些(希望是正确的)研究中得到的答案:
Here are the answers I've gotten from a bit of (hopefully correct) research:
两者都提供相同程度的同步.如果您通过 Collections.synchronized 将
Hashtable
包装起来,您将拥有相同的同步度,但有另一个冗余层.
Both provide the same degree of synchronization. If you were to wrap
Hashtable
through Collections.synchronized you would have the same degree, but with another redundant layer, of synchronization.
Hashtable
和 Collections.synchronizedMap(HashMap)
之间的主要区别更多存在于 API 级别.因为 Hashtable
是 Java 遗留代码的一部分,您会看到 Hashtable
API 得到增强以实现 Map
接口,成为Java 的集合框架.这意味着,如果您通过 Collections.synchronizedMap()
包装 Hashtable
,则包装的 Hashtable
的 API 将仅限于 地图
API.所以如果Hashtable
的API包含在你对行为的定义中,那么它显然被改变/限制了.
The main difference between Hashtable
and Collections.synchronizedMap(HashMap)
exist more at the API level. Because Hashtable
is part of Java's legacy code, you'll see that the Hashtable
API is enhanced to implement the Map
interface, to become part of Java's collections framework. This means that if you were to wrap Hashtable
through Collections.synchronizedMap()
, the API of the wrapped Hashtable
would become limited to the Map
API. So if the API of Hashtable
is encompassed in your definition of behavior, then it is obviously altered/limited.
这篇关于Hashtable 和 Collections.synchronizedMap(HashMap) 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!