Synchronization of constructors not allowed in Java - why?
In Java, synchronization of contructors is not allowed (results in a compile time error) as only the thread which is constructing the object should have access to the object and hence any other thread is not granted access until the construction of the object is complete. So, no explicit synchronization needed for constructors.
Caution: even though other threads will be given the access to an object only when it's already constructed, but if the constructor itself is allowing a memory leak then an imcomplete object can also be accessed by other threads which is obviously undesirable as the behavior is undefined. This may happen in case we are maintaining a Collection of instances (say with the reference 'instances') of the class and if the constructor is using the statement 'instances.add(this);' to add the current instance to the Collection then a half-baked object may be accessed by other threads.
Read next - static method/field synchronization >> The article tries to answer these questions: How does the static method synchronization differ from instance method synchronization? How do we ensure exclusive access to static fields being accessed in synchronized instance methods?
Liked the article? You may like to Subscribe to this blog for regular updates. You may also like to follow the blog to manage the bookmark easily and to tell the world that you enjoy GeekExplains. You can find the 'Followers' widget in the rightmost sidebar.