If i create a new thread inside a synchronized block, will the block remain locked till the thread execution is also complete? If not, then till when would it remain locked?
String sLine;
onClick(String line){
synchronized (lock) {
sLine = line;
new Thread(new Runnable() {
@Override
public void run() {
doProcessing(Sline);
}).start();
}
}
Only one thread per instance can execute inside a synchronized instance method.
When we use a synchronized block, Java internally uses a monitor, also known as monitor lock or intrinsic lock, to provide synchronization. These monitors are bound to an object; therefore, all synchronized blocks of the same object can have only one thread executing them at the same time.
Two threads cannot access the same synchronized method on the same object instance. One will get the lock and the other will block until the first thread leaves the method. In your example, instance methods are synchronized on the object that contains them.
Other threads will be able to continue synchronizing, and calling wait and notify. If the thread with the exception is holding some critical program logic resource, you may need to use try-finally to ensure it is released. Save this answer.
It would only remained locked if the code join()
d with the newly created thread, thus waiting for it to finish. As there is no join()
the lock will be released after the call to start()
has completed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With