3

In Java

suppose I am having a code like

class A {
    method A(){
        synchronized(this) 
        {
            this.B();
        }
    }
    method B(){
        //do modification stuff here
    }
}

My question is if one thread works on methodA and other on methodB, then how is my synchronized block getting protected.??

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
Argho Chatterjee
  • 579
  • 2
  • 9
  • 26

3 Answers3

3

if I understand your question correctly, you want to synchronize access to both methods:

class A{
  synchronized void A() {
     B();
  }
  synchronized void B() {
  }
}

That way, A() and B() will be gated using the same mutex, and if one thread tries to run B() while another one is already running A(), it will have to wait.

In the example you gave, if instead B() was a private method, and all your threads accessed the object via its A() method, you wouldn't have a problem, because the thread running B() would have already acquired the lock by entering the synchronized{} block in A().

Vlad
  • 18,195
  • 4
  • 41
  • 71
3

A synchronized block in Java is synchronized on some object. All synchronized blocks synchronized on the same object can only have one thread executing inside them at the same time. All other threads attempting to enter the synchronized block are blocked until the thread inside the synchronized block exits the block.

So in your Case

 method A(){
        synchronized(this) 
        {
            this.B();
        }
    }

Untill 1 thread exits from methodA() no other thread can enter it , So It's protected .

For Protecting Both Method you have to use like this

class A {
    method A(){
        synchronized(this) 
        {
            this.B();
        }
    }
    method B(){
        synchronized(this) 
            //do modification stuff here
        }
    }
}
Neeraj Jain
  • 7,643
  • 6
  • 34
  • 62
2

You would need to also synchronize in method B.

class A {
    method A(){
        synchronized(this) 
        {
            this.B();
        }
    }
    method B(){
        synchronized(this) 
            //do modification stuff here
        }
    }
}

P.S.: Since you're synchronizing around the whole body of the method, you can use the synchronized keyword in the method declaration:

public synchronized void methodA() {
    this.B();
}
M A
  • 71,713
  • 13
  • 134
  • 174
  • Are you saying that a thread can not enter `a.B()` while some other thread is working in a call to `a.A()` in the original example? How is that true? The thread that directly calls `a.B()` doesn't synchronize on _anything_. – Solomon Slow Feb 02 '15 at 20:09
  • @james large Doh! You're right. I was already assuming that the other thread also syncs in method B in my analysis... Updated. – M A Feb 02 '15 at 20:57