Learning the advantages of non-mutating objects when writing concurrent code
Now, let's imagine we are writing concurrent code that has to access the fields of the previously created instances. First, we will analyze the problems with the mutable version and then we will understand the advantage of working with the non-mutating object.
Imagine that we have two threads in which the code has a reference to the instance saved in mutableVector3d1
. The first thread calls the absolute
method for this mutating object. The first line of code for the absolute
method assigns the result of Math.abs
with the actual value of x
as an argument to the x
mutable field.
At this point, the method didn't finish its execution and the next line of code won't be able to access the values. However, concurrent code running in another thread that has a reference to this instance might access the values for the x
, y
and z
fields before the absolute
method finishes the execution. The object is in a corrupt state because...