Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java synchronized question

I'm new to Java Threads and synchronization.

Lets say I have:

public class MyClass(){

    public synchronized void method1(){ 
        //call method2();
    } 

    public synchronized void method2(){};

}
  1. What does it mean when I synchronize a method1() on an instance object? So when a thread acquired the lock when trying to access the synchronized method1(), does it prevent other threads to access another synchronized method2() from that same object?

  2. Lets say a thread acquires a lock when accessing method1(), but lets say that method1() makes a call to method2() which is also synchronized. Can this be possible? I mean are there any rules that can prevent method1() from calling method2()?

Thanks in advance.

like image 860
Marquinio Avatar asked Sep 11 '10 16:09

Marquinio


2 Answers

  1. Yes, using the synchronized method modifier on a non-static method means that it uses the monitor of the instance the method is invoked on, and this is shared between all such methods.
  2. No - the thread already owns the monitor, so it is free to enter other blocks protected by the same monitor.
like image 186
Michael Borgwardt Avatar answered Sep 20 '22 23:09

Michael Borgwardt


  1. See here:

    it is not possible for two invocations of synchronized methods on the same object to interleave. 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.

  2. Since this thread holds the lock on the current object, it can invoke method2(), and no other thread can.

like image 23
Bozho Avatar answered Sep 19 '22 23:09

Bozho