2

I'm familiar with basic java threading mechanism, however, got confused about one particular case. Below is the sample code.

static byte[] syncBuf;

// synchronized block of code
synchronized(syncBuf) {
  // Call non-synchronized method
  methodA(syncBuf);
}

My question is if multiple threads execute the above code, will the next thread block until methodA() is done executing since we are holding the lock on syncBuf which is passed by reference.

EDIT:

What happens if I change above code with the below:

static byte[] syncBuf;

// synchronized block of code
synchronized(syncBuf) {
  // Call non-synchronized method in a new thread
  new Thread(new Runnable() {
    @Override
    public void run() {
      methodA(syncBuf);
    }}).start();
}

Would the above interpretation still hold? Will the next thread block until methodA()-thread is done executing?

3 Answers 3

3

Your interpretation is (mostly) correct. Any other thread calling that code will block until the thread exits the synchronized block (which is slightly after methodA returns).

In Java, arrays are also objects that can be synchronized on.

You can always experiment and try it out to verify, either by using a debugger or with judicious use of the Thread.sleep function to see if other threads can get in.

Your edit is an entirely different case though - here, your main thread locks on syncBuf, starts a thread, then releases the lock. That thread does not acquire the lock (inside run()), so the call to methodA(syncBuf) does not acquire any locks or do any blocking. It would be the same as if the anonymous Runnable instance here were defined elsewhere (such as in its own class).

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, I tried doing all that. However, syncBuf neither gets messed up nor the calling thread gets blocked for long time before entering into synchronized block of code. Not sure how to verify it.
The above comment is for my edited question. I can verify it in the first case though. Calling threads do get blocked in the first case.
1

Regarding your edit

Would the above interpretation still hold? Will the next thread block until methodA()-thread is done executing?

No.

You create a new thread which invokes methodA asynchronously. From the point of view of the current thread, ie. the one that owns the lock on syncBuf, you've called the Thread#start() method, which returns immediately, and exited the synchronized block, releasing the lock.

Comments

0

Both the above answers by Chris and Sotirios Delimanolis are correct. I just marked the one as answer which covers both the cases.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.