简体   繁体   English

Collections.unmodifiable map 的替代品是什么,可以同时访问不可修改的 Map

[英]What is the alternative to Collections.unmodifiable map for concurrent access to unmodifiable Map

With the deprecation of edu.emory.mathcs.backport.java.util.Collections.unmodifiableMap , what is the alternative for concurrent access to UnmodifiableMaps?随着edu.emory.mathcs.backport.java.util.Collections.unmodifiableMap的弃用,并发访问 UnmodifiableMaps 的替代方案是什么?

You don't need to protect an UnmodifiableMap (or any immutable object for that matter) against concurrent access.您不需要保护 UnmodifiableMap(或任何不可变的 object )免受并发访问。

That's the whole point of immutability.这就是不变性的全部意义所在。

Collections.unmodifiableMap returns a view onto original map, not a copy Collections.unmodifiableMap返回原始 map 的视图,而不是副本

java.util.Collections.unmodifiableMap is not deprecated. java.util.Collections.unmodifiableMap未被弃用。

As for concurrent access to the map, you have no issue if using the refeference returned by this method.至于对map的并发访问,使用该方法返回的引用没有问题。 But beware: the returned reference is a view nack onto the original map.但请注意:返回的参考是原始 map 的视图。 So if the original map is changing while you are utilizing the unmodifiable view, you will have concurrency problems.因此,如果原始 map 在您使用不可修改视图时发生变化,您将遇到并发问题。

Map.copyOf

I suggest instead that in Java 10 and later you instead call Map.copyOf .我建议改为在 Java 10 和以后调用Map.copyOf This method makes an actual copy of the map rather than a view.此方法制作 map 的实际副本,而不是视图。 So the result is unrelated to the original.所以结果与原作无关。 Adding or removing entries in the original map has no effect on the non-modifiable map returned by this method.在原始 map 中添加或删除条目对该方法返回的不可修改的 map 没有影响。

Map< DayOfWeek , Person > map = new HashMap<>() ;
…
Map< DayOfWeek , Person > mapUnmod = Map.copyOf( fix 

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

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