简体   繁体   English

如何使非同步数据结构线程安全

[英]Ways to make non-synchronized data structure thread safe

I am wondering is there any other way to make a non-synchronized data structure to be thread safe other than using synchronized data structure like Hashtable and Vector , or using a wrapper like Collections.synchronizedList(List<T> arg) or Collections.synchronizedMap(Map<K,V> arg) ? 我想知道除了使用像HashtableVector这样的synchronized数据结构,或者使用像Collections.synchronizedList(List<T> arg)Collections.synchronizedMap(Map<K,V> arg)这样的包装器之外,还有其他方法可以使非同步数据结构成为线程安全的。 Collections.synchronizedMap(Map<K,V> arg)

I was asked on the interview that how to make a hashmap thread safe, and I told him to use Hashtable or ConcurrentHashMap or use the Collections.synchronizedMap wrapper, however, seems like these answers is not what he is looking for 我在面试中被问到如何使hashmap线程安全,我告诉他使用HashtableConcurrentHashMap或使用Collections.synchronizedMap包装器,但是,看起来这些答案并不是他想要的

Yes, you can make it immutable . 是的,你可以使它不可变 This is actually an excellent way to make code thread safe in many situations. 这实际上是在许多情况下使代码线程安全的绝佳方法。

Yes. 是。 If you do the synchronization of the construct yourself. 如果您自己同步构建。 But this is not recommended for apparent reasons... 但出于明显的原因,不建议这样做......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM