6

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

Dunith Dhanushka
  • 4,139
  • 6
  • 26
  • 29

3 Answers3

10

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
  • 115,893
  • 19
  • 128
  • 203
  • 1
    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 Jan 19 '10 at 17:53
  • 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 Jan 19 '10 at 17:59
  • 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 Jan 19 '10 at 18:15
5

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.

Matthias
  • 12,053
  • 4
  • 49
  • 91
  • 1
    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 Jan 19 '10 at 18:15
4

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
  • 93,734
  • 56
  • 203
  • 318