使数据结构线程安全的最有效方法(Java)

发布于 2025-01-07 07:57:40 字数 126 浏览 2 评论 0原文

我有一个共享的 Map 数据结构,需要线程安全。同步是读取或添加到 Map 的最有效方法吗?

谢谢!

编辑:数据结构是不可更新的缓存,即一旦填满就不会更新缓存。因此,最初有大量写入和一些读取,然后主要是读取

I have a shared Map data structure that needs to be thread-safe. Is synchronized the most efficient way to read or add to the Map?

Thanks!

Edit: The data structure is a non-updatable cache, i.e. once it fills up it does not update the cache. So lots of writes initially with some reads then it is mostly reads

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

菩提树下叶撕阳。 2025-01-14 07:57:40

当然,“最有效”是相对的,取决于你的具体情况。但是,如果您希望有很多,请考虑类似 ConcurrentHashMap线程同时处理地图;它是线程安全的,但仍然允许并发访问,这与 HashtableCollections.synchronizedMap() 不同。

"Most efficient" is relative, of course, and depends on your specific situation. But consider something like ConcurrentHashMap if you expect there to be many threads working with the map simultaneously; it's thread safe but still allows concurrent access, unlike Hashtable or Collections.synchronizedMap().

清音悠歌 2025-01-14 07:57:40

这取决于您在应用程序中如何使用它。

如果您对其进行大量读取和写入操作,则 ConcurrentHashMap 可能是最好的选择,如果它主要是读取,使用 ReadWriteLock 包装在集合内的通用 Map
(由于写入并不常见,因此只有在写入时才能获得更快的访问和锁定)。

Collections.synchronizedMap() 可能是最坏的情况,因为它可能只是给你一个所有方法同步的包装器,不惜一切代价避免它。

That depends on how you use it in the app.

If you're doing lots of reads and writes on it, a ConcurrentHashMap is possibly the best choice, if it's mostly reading, a common Map wrapped inside a collection using a ReadWriteLock
(since writes would not be common, you'd get faster access and locking only when writing).

Collections.synchronizedMap() is possibly the worst case, since it might just give you a wrapper with all methods synchronized, avoid it at all costs.

无法言说的痛 2025-01-14 07:57:40

对于您的特定用例(不可更新的缓存),写时复制映射将优于同步映射和 ConcurrentHashMap。

请参阅:https://labs.atlassian.com/wiki/display/CONCURRENT/CopyOnWriteMap 作为一个例子(我相信apache也有一个写映射实现的副本)。

For your specific use case (non-updatable cache), a copy on write map will outperform both a synchronized map and ConcurrentHashMap.

See: https://labs.atlassian.com/wiki/display/CONCURRENT/CopyOnWriteMap as one example (I believe apache also has a copy on write map implementation).

鯉魚旗 2025-01-14 07:57:40

同步方法或集合肯定会起作用。这不是最有效的方法,但实施起来很简单,除非每秒访问该结构数百万次,否则您不会注意到开销。

更好的主意可能是使用 ConcurrentHashMap< /a> - 这从一开始就是为了并发而设计的,并且应该在高度并发的情况下表现得更好。

synchronised methods or collections will certainly work. It's not the most efficient approach but is simple to implement and you won't notice the overhead unless you are access the structure millions of times per second.

A better idea though might be to use a ConcurrentHashMap - this was designed for concurrency from the start and should perform better in a highly concurrent situation.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文