0
Why are java immutable objects thread safe?
for example I have: Integer a = new Integer(0); and I pass this object to another thread. and in both of the threads, I write this code: a = a + 1; now I expect it to contain the number 2 after both threads are executed. but we know that incrementing an integer object by one means that you should first read what a contains, then increment it by 1, and then creating a new object, then copy its adress to var a. now thats more than one step. what if one thread started reading the data and increment it but...
3 ответов
0
but then suddenly it loses the cpu and the second thread starts reading the data (which is 0) and now they both create a new object containing 1. and the result is 1.
I mean if Integer class is thread safe itself, why do we need classes like AtomicInteger anyways?
0
That's the point. When you copy the object the old one is still there. You cannot change immutable objects so you cannot increment them.
So t1 tells t2: Look there is an Integer there.
And then t1 and t2 can do whatever with the thing. They will never know. Because the original Integer just stays there until no one points to it anymore. Then it gets collected.
So if those threads want to keep each other informed they have to do it again and again. Sharing a reference to an immutable is just a snapshot. A fixed point in time.
0
well I still didn't get it. are immutable objects thread safe or not? I heard that they are thread safe, if they are, then what is the need for AtomicInteger?