![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Can a constructor be synchronized in Java?
No, a constructor cannot be synchronized in Java. The JVM ensures that only one thread can invoke a constructor call at a given point in time. That is why no need to declare a constructor as synchronized and it is illegal in Java. However, we can use synchronized blocks inside a constructor.
If we are trying to put a synchronized keyword before a constructor, the compiler says that "error: modifier synchronized not allowed here".
Example
public class SynchronizedConstructorTest { // declaration of synchronized constructor public synchronized SynchronizedConstructorTest() { System.out.println("Synchronized Constructor"); } public static void main(String args[]) { SynchronizedConstructorTest test = new SynchronizedConstructorTest(); } }
Output
SynchronizedConstructorTest.java:3: error: modifier synchronized not allowed here public synchronized SynchronizedConstructorTest() { ^ 1 error
Advertisements