如何克隆同步集合?

MRa*_*ser 6 java collections synchronized

想象一下同步 Collection:

Set s = Collections.synchronizedSet(new HashSet())
Run Code Online (Sandbox Code Playgroud)

克隆此Collection的最佳方法是什么?

它首选克隆不需要在原始Collection上进行任何同步,但要求迭代克隆的Collection不需要在原始Collection上进行任何同步.

Boz*_*zho 7

在synchronized块中使用copy-constructor:

synchronized (s) {
    Set newSet = new HashSet(s); //preferably use generics
}
Run Code Online (Sandbox Code Playgroud)

如果您还需要同步副本,请再次使用Collections.synchronizedSet(..).

根据Peter的评论 - 你需要在原始集合的同步块中执行此操作.文档synchronizedSet是明确的:

当迭代它时,用户必须手动同步返回的集合

  • 不幸的是,它使用了发动机罩下的迭代器,因此您必须同步以安全地执行此操作. (3认同)