简体   繁体   English

有不可变(通常为ConcurrentHashMap)数据结构的正式模式,可以定期替换吗?

[英]Is there an official pattern for immutable (usually ConcurrentHashMap) data structure with ability for its replacement at intervals?

I find myself repeating the code of 我发现自己重复了

  1. store write only copy of datastructure and read only immutable ConcurrentHashMap 存储数据结构的只副本,只读不可变的ConcurrentHashMap
  2. readers are reading only from read only immutable HashMap no locks . 读者只能从只读的不可变HashMap中读取无锁
  3. Writer are writing to write only data structure (another ConcurrentHashMap) with locks. Writer正在写只写带锁的数据结构(另一个ConcurrentHashMap)。
  4. Every few minutes (depending on app needs) I switch the Read only datastructure which is a little old with the write only datastucture. 每隔几分钟(取决于应用程序的需求),我会切换“只读”数据结构,该结构与“只写”数据结构有点旧。 For this reason I use no locks here and I use a volatile only mark on the read only datastructure. 因此,我在这里不使用锁,并且在只读数据结构上使用易失性仅标记。

Is there an already published well know pattern with example code in java / official library which does that so that i don't have to create this pattern by myself? 在Java /官方库中是否已经存在一个带有示例代码的众所周知的模式,这样做是为了使我不必自己创建此模式?

Perhaps I don't fully understand your requirement, but why don't you read and write to the one instance of ConcurrentHashMap ? 也许我不完全理解您的要求,但是为什么不读写ConcurrentHashMap的一个实例呢? The whole point of a ConcurrentMap is that reading and writing to the maps between threads occurs in a thread-safe manner. ConcurrentMap的全部重点在于,以线程安全的方式对线程之间的映射进行读写。 Can you please explain why this can't occur in your case? 您能否解释一下为什么这种情况不会发生?

Read only immutable ConcurrentHashMap <-- this definitely doesn't make sense. 只读不可变的ConcurrentHashMap <-这绝对没有道理。 Any Map instance that's safely published (eg a plain old HashMap ), can be safely read by multiple threads. 任何安全发布的Map实例(例如,普通的HashMap )都可以由多个线程安全读取。 The only danger here is guaranteeing that the Map is only read from and not written to. 这里唯一的危险是低保Map只能读取和不能写入。 That guarantee can be made by using either Collections.unmodifiableMap() or Guava's ImmutableMap . 可以使用Collections.unmodifiableMap()或Guava的ImmutableMap做出保证。 It's also worth mentioning that it's best to ensure that the map entries themselves are immutable. 还值得一提的是,最好确保地图项本身是不可变的。

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

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