Pattern: Immutable State


This an oxymoron: immutable state!

By essence, an object’s state keeps mutating, according to the side effects experienced by the object. On the other side, we have the immutable value object. You just can not change it, you can only get a different instance that represents another value. Mutable objects are the bane of concurrent programming, where value objects thrive. But immutability comes at a great cost: the loss of identity.

Whatever you try to do, the number 2 cannot change to 8. The physical world is the world of mutability, stuff keeps changing: objects move, living things grow, stars explode, even atoms have a life expectancy. But, if change happens slowly we can get a decent sense of immutability: a pictures, even if it had a life of its own, its content is immutable, people on the snapshot will not move!

Same for a book: the paper may go yellow, the story will remain the same, which is important if we plan to read it: how could anyone read a book if its content kept changing. Now leave the physical world and go back to the virtual one: the situation is similar, stuff keep changing but we need them to be stable (and consistent) as long as we need them to execute some tasks. The usual approach to that was mutual access exclusion: if you are the one and only one to access the entity you need, you have full control on what may happen to it. But, as I pointed out numerous times, this approach just fails in the long run, if not in the short. Just to stress one pitfall out, one can assume that reads of the entity will outnumber writes, which leads to useless contention: no protection is required when there is no active writer. The usual solution relies on so-called read-write locks, which allow many readers but just a single writer. Better, yes, but it has its own pitfalls:

  • it can lead to writer starvation (so many readers that you cannot write)
  • it triggers tricky deadlocks due to lock promotion (when a reader needs to write)
  • most implementations have disappointing performances

How to efficiently address read vs. write contentions? What if the readers and writers did not compete? The only remaining contentions would be among writers, as readers happily share! Then use an immutable state:

  • readers can get a valid state whenever they need
  • writers just generate to state instances, without altering the preexisting ones

 

Advertisements

One thought on “Pattern: Immutable State

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s