3

I have the following snippet of code.

synchronized (mObject) {
    if (mObject.variable != -1) {
        doThis();
        doThisAsWell();
        andThis();
        insertObjectInDb(); // This is crashing because mObject.variable is -1
    }
}

To my knowledge, if I use synchronized on an object, and then run that block, the value of the variable can't be changed by any other thread, right? I don't understand how the value of the variable is -1, when I specifically check for that before entering the next block. And no, none of the functions in the block are changing the value. Have I completely misunderstood how these blocks work?

If it matters at all, this is all in a doInBackground() method of an async task in an android app.

Any ideas?

3 Answers3

6

To my knowledge, if I use synchronized on an object, and then run that block, the value of the variable can't be changed by any other thread, right?

No your assumption is wrong. synchronized is a monitor. The only guarantee you have is that the monitor is accessed by one thread at time.

Blackbelt
  • 156,034
  • 29
  • 297
  • 305
1

In this case, the object "mObject" doesn't become locked, rather the object "mObject" is used as the mutex and the body is prevented from executing concurrently with other code sections also synchronized on "mObject." It has no effect on other fields/methods of "mObject" that aren't synchronized.

Found some details here : Java synchronized method lock on object, or method? See the top comment on this.

Community
  • 1
  • 1
0

Afaik synchronized just says that any access to mObject is threadsafe means that following code would guaranteed set i to 3 if called in 3 threads

int i=0;
synchronized(i){
   i = i + 1;
}

What you want to use is a mutex

Verim
  • 1,065
  • 9
  • 17