Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of synchronized block inside constructor?

We can not make constructor synchronized but can write synchronized this inside constructor. In what case such requirement will come ? I am amused.

package com.simple;
public class Test {
    public Test() {
        synchronized (this) {
            System.out.println("I am called ...");
        }
    }

    public static void main(String[] args) {
        Test test=new Test();   
        System.out.println(""+test);
    }

    @Override
    public String toString() {
        return "Test []";
    }
}
like image 461
sailor Avatar asked Feb 22 '13 10:02

sailor


People also ask

Can we use synchronized block in constructor?

Note that constructors cannot be synchronized — using the synchronized keyword with a constructor is a syntax error. Synchronizing constructors doesn't make sense, because only the thread that creates an object should have access to it while it is being constructed.

What is the purpose of synchronized block?

A Synchronized block is a piece of code that can be used to perform synchronization on any specific resource of the method. A Synchronized block is used to lock an object for any shared resource and the scope of a synchronized block is smaller than the synchronized method.

Why would you use a synchronized block vs synchronized method?

Synchronized blocks provide granular control over a lock, as you can use arbitrary any lock to provide mutual exclusion to critical section code. On the other hand, the synchronized method always locks either on the current object represented by this keyword or class level lock, if it's a static synchronized method.

What is the purpose of synchronized statement?

A synchronized statement can be used to acquire a lock on any object, not just this object, when executing a block of the code in a method. This block is referred to as a synchronized block.


2 Answers

Well, you could start a new thread within the constructor. It would be highly unusual - and certainly in the code you've provided it would be pointless - but it could happen.

Languages don't typically try to find every possibly thing you could do that would be pointless - it would lead to a very complex language specification. There has to be some degree of thought on the part of the language users, too...

like image 126
Jon Skeet Avatar answered Oct 13 '22 12:10

Jon Skeet


Synchronizing on this would be a sign of bad practice because it would imply you are leaking this out of the constructor: this is the only way you could have some other code synchronizing on the same object.

Synchronizing on some other common lock, however, could be legitimate: the constructor my indeed involve calling some code that requires such synchronization.

like image 30
Marko Topolnik Avatar answered Oct 13 '22 13:10

Marko Topolnik