Can Constructors Be Synchronized in Java?


synchronized in java

*This post may contain affiliate links. As an Amazon Associate we earn from qualifying purchases.

During your IT interview, you may be asked if constructors can be synchronized in Java. You should know is that this is a trick question and that you will be expected to answer it properly to make a good impression. Let us tell you all about this matter so that you can answer this question properly.

Can Constructors Be Synchronized in Java?

The answer that you are expected to give to this question is a hard no. In fact, using the ?synchronized? keyword in a constructor would actually lead to a syntax error, so you need to make sure that you are very adamant.

You should begin your explanation by pointing out that the ?synchronized? keyword is commonly used to make sure that two or more threads do not access a method group before one of these threads completes the execution in those specific methods.

Why Synchronizing a Constructor Might not Make Sense

The main thing you should know about constructors is that they only require access to one thread. Constructors are used to restrict object creation to one value. As such, the constructor only needs to have access to that thread that creates the object.

Therefore, synchronizing a constructor doesn’t make sense because it does not require access to more than one thread, while the ?synchronize? keyword needs a minimum of two threads to be used.

So make sure your point out to the interviewer that constructors cannot be synchronized in Java and that you provide the complete explanation as to why this does not make sense in Java.

Image Source:?Flickr

Recent Posts