固定大小的并发地图 [英] Concurrent Map with fixed size

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

问题描述

我需要一张具有以下要求的地图:

I need a map with the following requirements :

  1. 它应该是高度并发的.多个线程可以同时调用put()get()remove()方法.

它应该是固定大小.如果HashMap的大小达到最大值(例如10000),则不应在地图上添加新条目.不能是LRU高速缓存,其中最早的条目在达到最大大小时会被删除.

It should be of fixed size. If the size of the HashMap reaches to the max value (e.g. 10000), addition of a new entry to the map should not be allowed. It CAN'T be LRU cache where the oldest entry gets removed on reaching maximum size.

ConcurrentHashMap可以满足#1.但是,不确定如何在ConcurrentHashMap上实现#2而不影响并发性(添加自定义put()方法,该方法仅在大小小于最大大小时才会添加到映射中,需要同步")这将使使用并发HashMap的目的无效.

ConcurrentHashMap may satisfy #1. But, not sure how #2 can be implemented on top of ConcurrentHashMap without impacting concurrency (Adding a custom put() method which will add to the map only when the size is lesser than the max size, needs to be "synchronized". That will defeat the purpose of using concurrent HashMap).

请让我知道您的想法.

Please let me know your thoughts.

推荐答案

您可以使用计数信号量来限制委托给ConcurrentHashMap的地图,以限制地图中的项目数量. 信号量类在原子上使用-更新了int以跟踪许可证,因此不会产生太多额外的开销.

You could implement a map that delegates to a ConcurrentHashMap, using a counting semaphore to limit the number of items in the map. The Semaphore class uses an atomically-updated int to keep track of the permits, so it wouldn't incur much extra overhead.

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

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