日志文章

2007年12月25日 16:56:21

EnumMap<K extends Enum<K>, V>类为非线程安全

Like most collection implementations <tt>EnumMap</tt> is not synchronized. If multiple threads access an enum map concurrently, and at least one of the threads modifies the map, it should be synchronized externally. This is typically accomplished by synchronizing on some object that naturally encapsulates the enum map. If no such object exists, the map should be "wrapped" using the method. This is best done at creation time, to prevent accidental unsynchronized access:

    Map<EnumKey, V> m = Collections.synchronizedMap(new EnumMap(...));
参考译文:
像很多的collection 实现类一样,EnumMap也不是线程同步的。当多线程访问该EnumMap,至少一个线程更改此EnumMap,必须使用线程同步。一搬的办法是,用某对象封装此enum map。如果没有这样的保证对象存在,需要用“封装”方法来封装次enum map。最好的办法是,在创建之初,进行封装,阻止意外的非同步访问。

类别: java 基础知识 |  评论(0) |  浏览(695) |  收藏
发表评论