Search code examples
javamultithreadingsynchronize

Why we can't declare whole class as synchronized in Java?


I am new to Java I just want to know what if whole class in Java will be synchronized, what will be the possible problems? I know the concept of class level locking, which is different.


Solution

  • Marking the whole class synchronized would be misleading. Although there are situations when it makes perfect sense to make all methods of a class synchronized, a class typically contains other declarations that cannot be synchronized.

    For example, class constructor cannot be marked synchronized. Same goes for fields of a class. One could mistakingly assume that fields in a class marked synchronized would be accessed in a synchronized way, but that is not something that Java does automatically. Of course language designers could declare that synchronized on class level applies only to methods, but such decision would be somewhat arbitrary.