I have a Res class that contains a synchronized method A and an unsynchronized method B. In another class, I create an instance of the Res class and two threads: I assign the synchronization method A to the Res class for the first thread and assign the unsynchronized method B to the second thread for the same instance of Res. From the literature, I realized that if a synchronized method gets control, the calling thread activates a monitor that blocks an object for other threads, that is, in my example, you must first fully work out method A, and only then method B. However, I checked and it turns out that For some reason, B works in parallel with method A. If I make method B also synchronized, then this parallelism disappears. It turns out that if a synchronized method was invoked for an object in one thread, then an unsynchronized method can run in parallel for another object for the same object? That is, the possibility of executing for an object from another thread only synchronized methods is blocked, and unsynchronized methods can be executed?

public class Res { int number = 0; public synchronized void A(){ for (int i = 0; i<10000; i++) { number += 1; System.out.println(number); } } public void B(){ for (int i = 0; i <10000; i++) number-=1; } } public class Threads { Res commonRes = new Res(); public void startThreads(){ new Thread(()->commonRes.A()).start(); new Thread(()-> commonRes.B()).start(); } } 
  • one
    Add the code, if possible, it will be easier to navigate - Alex Tremasov
  • "the calling thread activates a monitor that blocks the object for other threads" if they call synchronized methods of the same object. - Sergey Gornostaev pm

1 answer 1

Non-synchronized methods do not need a monitor (unless, of course, within this method there is no monitor capture via synchronized (...)). When you write non-static synchronized methods, they capture the monitor of the current instance before execution. That is, so to speak, not the current instance - but its monitor. Therefore, other non-synchronized non-static methods can work quietly from any stream - they do not need a monitor. In the case of static synchronized methods, the capture of the monitor is no longer an instance of the class, but of the class itself. In large applications, if you want the monitor to be captured only by your code, you need to create a special object that is not available to other code, the monitor of which your streams will capture.