实现并发的LinkedHashMap [英] Implementing a concurrent LinkedHashMap

查看:664
本文介绍了实现并发的LinkedHashMap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为多线程架构创建一个并发的LinkedHashMap。

I'm trying to create a concurrent LinkedHashMap for a multithreaded architecture.

如果我使用 Collections#synchronizedMap(),我必须使用同步块进行迭代。

If I use Collections#synchronizedMap(), I would have to use synchronized blocks for iteration. This implementation would lead to sequential addition of elements.

如果我使用 ConcurrentSkipListMap 有任何方法来实现 Comparator 以存储在链接列表或队列中的顺序存储。

If I use ConcurrentSkipListMap is there any way to implement a Comparator to store sequentially, as stored in Linked List or queue.

我想使用java的内置而不是

I would like to use java's built in instead of third party packages.

编辑:

在此并发 LinkedHashMap ,如果键是名称,我希望把键按顺序到达。

In this concurrent LinkedHashMap, if the keys are the name, I wish to put the keys in sequence of their arrival. i.e. new value would be appended to either at start or end, but sequentially.

在迭代时, LinkedHashMap 可以添加新条目或删除。

While iterating, the LinkedHashMap could be added with new entries, or removed. but the iteration should be the sequence in which the entries were added.

我理解,通过使用 Collections#synchronizedMap(),需要实现用于迭代的同步块,但是在迭代时映射是可修改的(可以添加/删除条目)。

I understand that by using Collections#synchronizedMap(), an synchronized block for iteration would have to be implemented, but would the map be modifiable (entries could be added/removed) while it is being iterated.

推荐答案

A LinkedHashMap 有一个通过哈希表运行的双向链表。 FIFO仅在写入(插入或移除)时突变链接。

A LinkedHashMap has a doubly linked list running through a hashtable. A FIFO only mutates the links on a write (insertion or removal). This makes implementing a version fairly straightforward.


  1. 编写LHM只允许插入顺序。


  2. 保护 #put() / #putIfAbsent() / #remove()有锁。


  1. Write a LHM with only insertion order allowed.
  2. Switch to a ConcurrentHashMap as the hashtable.
  3. Protect #put() / #putIfAbsent() / #remove() with a lock.
  4. Make the "next" field volatile.

在迭代时,不需要锁定,因为您可以安全地按照下一个字段。读取可以通过在 #get()上委托CHM来实现无锁定。

On iteration, no lock is needed as you can safely follow the "next" field. Reads can be lock-free by just delegating to the CHM on a #get().

这篇关于实现并发的LinkedHashMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆