简体   繁体   English

我应该使用ConcurrentHashMap或Hashmap还是SynchronizedMap?

[英]Should I use ConcurrentHashMap or Hashmap or SynchronizedMap?

I have created a hashmap outside my mutithreading code. 我在多线程代码之外创建了一个哈希表。 There are going to be no changes in this hasmap later. 以后,此hasmap中将不会有任何更改。

After this, I am starting two threads which will both be reading from this hashmap(yes, only read operations). 在此之后,我将启动两个线程,这两个线程都将从该哈希图中读取(是的,仅读取操作)。 If thread1 is reading from my hashmap object , can thread 2 also read at the same time? 如果thread1正在从我的hashmap对象读取,则线程2也可以同时读取吗? Or do I need a Concurrenthashmap or any other version of Map? 还是我需要Concurrenthashmap或任何其他版本的Map?

No you don't need concurrent Hash maps..but only since you don not do any modifications. 不,您不需要并发的Hash映射。但是仅因为您不进行任何修改即可。 You can read the same without any problem. 您可以毫无问题地阅读相同内容。

If thread1 is reading from my hashmap object, can thread 2 also read at the same time? 如果线程1正在从我的哈希映射对象中读取,线程2是否也可以同时读取?

If you are sure that there are no write operations then you need not use Synchronization options at all, Go for a normal version of Map. 如果确定没有写操作,则根本不需要使用“同步”选项。

You can also use Immutable Map 您还可以使用不可变地图

A Map whose contents will never change, with many other important properties detailed at ImmutableCollection 一个地图,其内容永远不会改变,其其他重要属性在ImmutableCollection中进行了详细介绍

如果只需要读操作,则无需使用同步。如果创建后未进行任何写操作,则使其不可变,因此没有主体可以更改它。不需要同步。

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

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