Reputation: 2357
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?
Upvotes: 2
Views: 893
Reputation: 2357
Both the above answers by Chris and Sotirios Delimanolis are correct. I just marked the one as answer which covers both the cases.
Upvotes: 0
Reputation: 16215
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).
Upvotes: 3
Reputation: 279920
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.
Upvotes: 1