What is the relationship with thread-safety and immutable objects? Does it makes easier to share a single resource among multiple threads? If immutable objects are stateless, can they be pooled in a container like a J2EE container?
thanks
What is the relationship with thread-safety and immutable objects? Does it makes easier to share a single resource among multiple threads? If immutable objects are stateless, can they be pooled in a container like a J2EE container?
thanks
Immutable Object: An object that doesn't change its internal state.
The relationship with thread-safety: if an object cannot be mutated, it is safe to use it across threads i.e. no need to have locks or the like to ensure consistency across threads.
Immutable objects are objects that can not be changed. If an object can not be changed, then there is no concern that a competing thread will change the object state "behind the back" of the executing thread, and therefore immutable objects do not need to be protected via synchronization or some other technique.
Threadsafe objects are objects which allow to be accessed concurrently by multiple threads. Their implementation guarantees (for example by lockings / synchronzized methods / ...) that they will not get into a invalid state. In addition, there should be no loss of data.
Immutable objects may not be altered after their creation. So: Yes, they are some kind of stateless.
As immutable objects can not be changed, there is no need for locking - reading access to objects is always threadsafe (when not modifying variables). Therefore, real immutable objects are always threadsafe.