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?
A POJO can't be thread safe. A POJO is just data, and thread safety is not a property of data alone: Thread safety is a property of the methods that access the data.
ConcurrentHashMap class is thread-safe i.e. multiple threads can operate on a single object without any complications.
A method will be thread safe if it uses the synchronized keyword in its declaration.
— Hashmap can solve performance issue by giving parallel access to multiple threads reading hashmap simultaneously. But Hashmap is not thread safe, so what will happen if one thread tries to put data and requires Rehashing and at same time other thread tries to read data from Hashmap, It will go in infinite loop.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With