5

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

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?

richj
  • 7,499
  • 3
  • 32
  • 50
CodingHero
  • 2,865
  • 6
  • 29
  • 42

1 Answers1

12

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

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

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.

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.


A piece of advice:

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.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • +1 for the last bit. Multi-threaded apps can become complex rather quickly, and the art of resource synchronization is one that takes a long time to master. Simply synchronizing everything and making things volatile is never enough. I recommend doing some reading about concurrency in Java, since there's more than just synchronization and volatility to worry about for shared resources, such as operation atomicity. – Brian Aug 03 '13 at 08:00