This article talks about Java's "synchronized" keyword.
...
private int foo;
public synchronized int getFoo() { return foo; }
public synchronized void setFoo(int f) { foo = f; }
If a caller wants to increment the foo property, the following code to do so is not thread-safe:
...
setFoo(getFoo() + 1);
If two threads attempt to increment foo at the same time, the result might be that the value of foo gets increased by one or by two, depending on timing.
Now, my question:
Why doesn't "synchronized" on setFoo() prevent the above bolded line?
Then each of them add one and call setFoo, and the end result is that foo gets incremented only once, instead of twice
Why? – Calcine