Java threads are "synchronized"

This article talks about the Java keyword "synchronized".

  ...
  private int foo;
  public synchronized int getFoo() { return foo; } 
  public synchronized void setFoo(int f) { foo = f; }

If the caller wants to increase the foo property, the following code is not thread safe for this:

  ...
  setFoo(getFoo() + 1);

If two threads try to increase foo at the same time, the result may be that the value of foo increases by one or two depending on the time.

Now, my question is:

Why is it not syncing with setFoo () to prevent the line from appearing in bold?

+5
source share
6 answers

This is an example of a check-action-action race condition.

A scenario may occur as shown below:

Thread-1 getFoo() returns 0
Thread-2 getFoo() returns 0
Thread-2 setFoo(1)
Thread-1 setFoo(1)

, foo, .

, , getFoo() setFoo(), , , .

+6

, foo , foo , , , ( ) , get() set()

:

int temp = getFoo(); //safe method
temp = temp+1; //not protected here - im not holding any locks ...
setFoo(temp); //safe method
+6

synchronized , getFoo, getFoo, . setFoo, , foo , . , .

, , get set.

public synchronized void addFoo(int addend)
{
   foo += addend;
}
+4

, , getFoo "" setFoo.

setFoo(){
   //getFoo();
   //...
}

, getFoo setFoo. , :

public static int foo(int i) {
    System.out.print("FOO!");
    return i;
}

public static int bar(int i) {
    System.out.print("BAR!");
    return i;
}

public static void main(String[] args) throws Exception {
    System.out.println(foo(bar(1)));
}

:

BAR!FOO!1

, bar foo. , , ( ) getFoo, , setFoo. , 0, setFoo, 1.

+1

?

class C {
  private int foo;
  public int getFoo() { return foo; } 
  public void setFoo(int f) { foo = f; }
}

C myC = new C();
synchronized(myC) {
  int foo = myC.getFoo();
  myC.setFoo(foo + 1);
}
println(myC.foo);
0

All Articles