如果存储在concurrentHashMap中,POJO对象中的可变字段是否安全? [英] Are mutable fields in a POJO object threadsafe if stored in a concurrentHashMap?

查看:195
本文介绍了如果存储在concurrentHashMap中,POJO对象中的可变字段是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果存储在concurrentHashMap中,POJO对象中的可变字段是否属于线程安全?

Are mutable fields in a POJO object threadsafe if stored in a concurrentHashMap?

或者我是否需要使用锁定来获取字段或使其变为波动以确保更新所有线程都能看到?将该字段标记为volatile是否足以确保所有线程都能看到更新?

Or do I need to gaurd the fields with a lock or make them volatile to ensure upates are seen by all threads? Will marking the field as volatile be enough to ensure updates are seen by all threads?

推荐答案


是POJO对象线程安全中的可变字段(如果存储在concurrentHashMap中?)

are mutable fields in a POJO object threadsafe if stored in a concurrentHashMap?

否。唯一线程安全的是对hashmap本身的操作。

No. The only thing that is thread-safe is the operations on the hashmap itself.


或者我是否需要使用锁定或让它们变得易变,以确保所有线程都可以看到upates?

Or do I need to graud the fields with a lock or make them volatile to ensure upates are seen by all threads?

是的,虽然这不一定足够。

Yes, though this is not necessarily sufficient.


将字段标记为volatile是否足以确保所有线程都能看到更新?

Will marking the field as volatile be enough to ensure updates are seen by all threads?

这取决于类型田野。对于参考类型,它还取决于对象是否可变。

It depends on the types of the fields. For reference types, it also depends on whether the objects are mutable.

一条建议:

您不能通过简单的策略来处理线程安全,例如使一切变得易失或同步。您实际上需要了解技术,并了解应用程序的性质;即并发/多线程将如何发生,以及需要是线程安全的。

You can't deal with thread-safety by simple strategies like making everything volatile or synchronized. You actually need to understand the technology, and also understand the nature of your application; i.e. how the concurrency / multi-threading is going to happen, and what needs to be thread-safe.

这篇关于如果存储在concurrentHashMap中,POJO对象中的可变字段是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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