What are immutable objects?

What is the relationship with thread safe and immutable objects? Is it easier to split a single resource between multiple threads? If immutable objects have no state, can they be combined into a container, for example, a J2EE container?

thanks

+6
immutability multithreading
source share
3 answers

Threadsafe objects are objects that allow you to access multiple threads at the same time. Their implementation guarantees (for example, locks / synchronized methods / ...) that they will not fall into an invalid state. In addition, there should be no data loss.

Immutable objects cannot be modified after they are created. So: Yes, this is some kind of stateless person.

Since immutable objects cannot be changed, there is no need for locking - reading access to objects is always thread-safe (when it does not change variables). Therefore, real immutable objects are always thread safe.

+5
source share

Immutable objects are objects that cannot be changed. If the object cannot be modified, then there is no concern that a competing thread will change the state of the object "behind" the executable thread, and therefore immutable objects do not need to be protected by synchronization or any other technique.

+10
source share

Immutable object: an object that does not change its internal state.

Relationship with thread safety: if an object cannot be mutated, it is safe to use it in threads, i.e. no locks or the like are needed to ensure thread consistency .

+4
source share

All Articles