Implementing a concurrent LinkedHashMap

后端 未结 5 782
面向向阳花
面向向阳花 2021-01-04 06:15

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

If I use Collections#synchronizedMap(), I would have to use synchroni

5条回答
  •  抹茶落季
    2021-01-04 06:36

    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. 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.

    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().

提交回复
热议问题