Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execution of new thread inside a synchronized block

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(); 
    }
}
like image 235
Sunny Avatar asked Apr 10 '13 12:04

Sunny


People also ask

How many threads per instance can execute inside a synchronized?

Only one thread per instance can execute inside a synchronized instance method.

What happens internally when a method is synchronized?

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.

Can two threads access a synchronized method 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.

What happens if a thread throws an exception inside synchronized block?

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.


1 Answers

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.

like image 130
hmjd Avatar answered Oct 17 '22 15:10

hmjd