Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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?

like image 803
CodingHero Avatar asked Aug 03 '13 07:08

CodingHero


People also ask

Is POJO thread-safe?

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.

Is ConcurrentHashMap always thread-safe?

ConcurrentHashMap class is thread-safe i.e. multiple threads can operate on a single object without any complications.

How can you tell if an object is thread-safe?

A method will be thread safe if it uses the synchronized keyword in its declaration.

Can I use HashMap where multiple threads are accessing updating it explain further?

— 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.


1 Answers

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.

like image 174
Stephen C Avatar answered Nov 09 '22 16:11

Stephen C