Achieve thread-safety with immutability

Immutability vs. mutability

Mutable objects are different control in a multi-threaded environment and are prone to cause strange bugs and unexpected behaviors in your code. We are going to investigate why it’s usually better to work with immutable objects and learn good design patterns to help you as a developer achieve immutability.

Why is mutability dangerous?

Many applications today utilize multiple threads to spread the workload across multiple processor cores. For example in an application, it is normal to keep the GUI on a separate thread. Otherwise, you would have the GUI being blocked until the back-end has finished processing stuff. But what happens when thread A has an object and then thread B updates it? Let’s construct a basic test for this.

Here we got a Person class. A person has a name, a city and a list of favorite dishes. The constructor for MutablePerson will create objects are, as you probably guessed, mutable.

The following method creates a MutablePeson object and then a separate thread simulates some work and updates the person’s city. Simultaneously, our initial thread checks if the city is Stockholm, and if so simulate some work and then print out the city. Running our little method produces the following output:

Viktor lives in Gothenburg

This is not great, as we had a test for Stockholm we expect the person’s city to be Stockholm as well when printing it out. Let’s take a look at another example, something a bit more serious, mutable lists. Let’s introduce another person, Anastasia. She likes the same food. So she decides to use the same list of favorite foods as Viktor.

But Anastasia also loves Sushi, so she adds that to her list.

Viktor then gets hungry and decides to order some food. He looks at his list of favorite foods to help him decide on what to buy.

Pizza
Tacos
Steak
Sushi

But wait, what? Viktor hates Sushi, this is a disaster!

Immutability

We saw how potentially dangerous mutability can be. So let’s attempt to create an immutable person class. I am going to introduce you to something referred to as the builder pattern. The builder patterns make it possible to force immutability by using final modifiers on all the instance variables without having a super long constructor where everything has to be set. With the final modifier and/or not providing any setter methods directly on the person class, we can be sure that our object never mutates without us knowing it.

The builder pattern often introduces a nested inner building class, where you build up the object before constructing it. When we feel ready to construct our person class we can then call the build method.

We also make copies of the list and setting and retrieving the list, so that nobody outside the actual the object itself can modify their list. Let’s try the previous methods that we created with this ImmutablePerson object instead.

As you noticed, there isn’t even any setter to modify the instance variables, instead, we have to build a ImmutablePerson. And as you probably expected the output to be:
Viktor lives in Stockholm

Let’s try our other example as well.

And the output was:

Pizza
Tacos
Steak

Viktor didn’t risk end up eating something that he didn’t enjoy! So then you may wonder, how do you edit objects? Well, you don’t. Instead, you create a new object from the existing one. I have provided an easy way to do this with toBuilder(), which returns a builder from the object.

Final words

We have investigated the benefits of switching over and sticking to immutable objects. Of course, my examples have been a bit extreme, but it was just to prove a point. Mutable objects are a hazard in a multi-threaded application, dealing with mutable objects requires the developer to be very cautious. So why not switch over to immutable objects and get rid of that burden?

The builder pattern and immutable objects go hand in hand, so I suggest that you start using them more if you aren’t already.

The source code for this blog can be found on my GitHub here.

If you enjoyed this post, please help me out by giving it a like and sharing it on social media.

You may also like

2 Comments

  1. So Viktor is now bound to Stockholm for good, hope he likes it there. Also it’s nice that his favorite dishes now remain the same, even if Anastasia specifically asks to share his instance of the list. Your examples certainly seem a bit extreme.
    Why is there no demonstration of how one would work with the immutable objects. Obviously there’s a requirement for being able to change the properties of a Person post-instatiation, otherwise just omit the setters from the mutable version, wrap favorite foods in a Collections.unmodifiableList() and be done with it.

    1. Hi, it’s actually quite simple and I provided a method exactly for this but probably I didn’t make it clear enough and that’s my fault I will update the post later tonight with an example of this.

      In the ImmutablePerson class there is a method where you create a new builder from the object.

      With the builder object returned you can create a new object with updated values. The whole point is that you shouldn’t be allowed to modify an object. You can only create new ones.

Leave a Reply

Your email address will not be published. Required fields are marked *