Reputation: 261
say, I have a lot of read operations and a few write operations, and the object which will be placed in map is quite "heavy"-initialization of such object costs much memory/time,etc.
how should I code to both utilize the high performance of concurrenthashmap and ensure a minimum cost of unnecessary initialization of those cached objects.
sample code snippet is welcome and greatly appreciate! Thanks!
Upvotes: 2
Views: 1394
Reputation: 425318
The code in ConcurrentHashMap is highly optimized - I would just use it.
The concurrency overhead is minimal if there are few updates. If a write operation occurs during a read, there is some overhead when a temporary copy of the internal state is made, but otherwise the difference in performance in negligible. I would use the provided class as is and only if you find you are getting performance problems, then look into using something else.
Note that the initialization cost is not relevant to concurrency performance, only the operation of adding it to the map is.
Upvotes: 1
Reputation: 53694
Pretty sure guava has exactly what you are looking for, see MapMaker.makeComputingMap.
Upvotes: 2
Reputation: 3838
It depends on your requirements, but you may consider using a Pool
of instances to reduce the instantiation count. That will improve your performance if you are currently dumping items from the map to garbage collect them, so instead of GC, you place them back in the pool and re-use them later.
Upvotes: 0