A look at the synchronized modifier (6/14/99)
The JavaWorld experts answer your most pressing Java questions — every week
Q: What does the ‘synchronized’ modifier for a class declaration do? I see decompilers generating the code and javac compiling it without difficulty. Example:
public synchronized class HelloWorld {}
A: synchronized
is not a valid modifier for a class. According to the Java Language Specification (JLS 8.1.2, see Resources), public
, abstract
, and final
are the only valid modifiers for a top-level class. Inner classes can also be private
, protected
, or static
. Therefore, the compiler should reject the code in your example. In fact, this is a known bug, fixed in JDK 1.2.
Out of curiosity, we checked to see if the synchronized
modifier on a class had any effect in the generated code. We tried compiling a class with several different kinds of methods (abstract
, final
, static
, and so on) with and without the synchronized
keyword. The class files generated were exactly the same.
It is also a bug for a decompiler, such as javap
, to report classes as being synchronized
. In fact, javap
claims that every class is synchronized
. This bug is also fixed in JDK 1.2. Documentation on these two bugs and others can be found in the Bug Parade on the Java Developer Connection Website. (See Resources below.)