Pregunta

According to Wikipedia, a thread safe code is guaranteed to be free of race conditions and after going through internet, it seems that immutable objects are inherently threadsafe and does not require any additional synchronization. However, I am not able to understand how is that possible. For example lets say I have an immutable class Counter.

    public class Counter{
       private final int counter;
       public Counter(int counter){
          this.counter = counter;
       }
       public int getCounter(){ return counter;}
       public Counter incrementCounter(){
          return new Counter(counter+1);
       }
     }

Now lets say I create an object of counter with value 0. Two threads simultaneously access the object with value 0, increments it and ends with two different objects of counter, both with value 1. But doesn't this causes race condition?? By using synchronized blocks, I will get a single object with counter value of 2 as expected but not using Immutable objects. Even though immutable objects are thread safe for reading but do they need external synchronization while writing?

¿Fue útil?

Solución

If the threads "just" increase the counter and keep the object for themself, there is no problem. A problem would be if the threads want to store the new object where the old 0-counter was (and this variable is not immutable)

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top