views:

147

answers:

3

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

+3  A: 

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.

jldupont
+8  A: 

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.

Will Hartung
also if the object is stateless is pointless to talk about immutability, because there is no state to mutate. So is safe to pool the objects in a container.
Mauricio
One thing to consider is that if you do try to change an immutable object (say, a string) by reassigning a variable pointing to that object, then other threads will not see that change. So "changes" to an immutable object cannot be shared across threads.
Aaron
If you try and 'change' any object by reassigning a variable which references that object, then you don't know what you're doing.
Pete Kirkham
+4  A: 

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.

winSharp93
Normally stateless objects have no state. Immutable objects cannot transition to a different state from the one they were created in, so they have exactly one state.
Pete Kirkham