Does java have a “LinkedConcurrentHashMap” data structure?

前端 未结 8 1709
猫巷女王i
猫巷女王i 2020-12-01 07:08

I need a data structure that is a LinkedHashMap and is thread safe.

How can I do that ?

8条回答
  •  伪装坚强ぢ
    2020-12-01 07:59

    There's a number of different approaches to this problem. You could use:

    Collections.synchronizedMap(new LinkedHashMap());
    

    as the other responses have suggested but this has several gotchas you'll need to be aware of. Most notably is that you will often need to hold the collections synchronized lock when iterating over the collection, which in turn prevents other threads from accessing the collection until you've completed iterating over it. (See Java theory and practice: Concurrent collections classes). For example:

    synchronized(map) {
        for (Object obj: map) {
            // Do work here
        }
    }
    

    Using

    new ConcurrentHashMap();
    

    is probably a better choice as you won't need to lock the collection to iterate over it.

    Finally, you might want to consider a more functional programming approach. That is you could consider the map as essentially immutable. Instead of adding to an existing Map, you would create a new one that contains the contents of the old map plus the new addition. This sounds pretty bizarre at first, but it is actually the way Scala deals with concurrency and collections

提交回复
热议问题