Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preempting a thread that is executing synchronized method

Give the following code

    class Test{
       double x;
       public void synchronized a()
       { 
          x = 0;
          //do some more stuff
       }
       public void b() 
       { 
          x = -1; 
       } 
    }

Can the thread in a(), in the middle of modifying x be preempted by a thread that calls b() on the same object?

Isn't synchronized method be executed like one single atomic operation?

I believe the other way is possible(thread in b() can be preempted by the thread that calls a() on the same object since b() is not guarded my the Test object lock).

Can some one shed some light on this?

like image 285
FourOfAKind Avatar asked May 25 '11 11:05

FourOfAKind


People also ask

What will happens if a synchronized method is called?

When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.

What will happen if a synchronized method is called by two threads?

No. If a object has synchronized instance methods then the Object itself is used a lock object for controlling the synchronization. Therefore all other instance methods need to wait until previous method call is completed.

How many threads per instance can execute inside a synchronized instance method?

Only one thread per instance can execute inside a synchronized instance method.


1 Answers

synchronized only stops other threads from acquiring the same monitor. It in no way makes the operation atomic. In particular:

  • Side-effects of the method can be observed by other threads which aren't trying to synchronize on the same monitor
  • If an exception occurs, there's no sort of roll-back
  • Other threads can access and modify the same data used by the synchronized method, if they aren't synchronized on the same monitor

b() isn't synchronized, so it's entirely possible for one thread to be executing a() and another to be executing b() at the same time.

like image 84
Jon Skeet Avatar answered Sep 29 '22 18:09

Jon Skeet