java 并发实战 对象组合问题

第55页 程序清单4-8

public Map<String, Point> getLocations() {
        return Collections.unmodifiableMap(
                new HashMap<String, Point>(locations));
    }

代码上方有一句话:
其中只返回一个HashMap,因为getLocations并不能保证返回一个线程安全的Map。

getLocations到底是不是线程安全,希望对并发了解可以给予一些指点,谢谢

阅读 3.1k
1 个回答

getLocations 非线程安全。但是``返回的集合是只读集合,故返回的map是线程安全的。
oracle官方文档解释如下:

public static <K,V> Map<K,V> unmodifiableMap(Map<? extends K,? extends V> m)
Returns an unmodifiable view of the specified map. This method allows modules to provide users with "read-only" access to internal maps. Query operations on the returned map "read through" to the specified map, and attempts to modify the returned map, whether direct or via its collection views, result in an UnsupportedOperationException.
The returned map will be serializable if the specified map is serializable.

Parameters:
m - the map for which an unmodifiable view is to be returned.
Returns:
an unmodifiable view of the specified map.
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题