Search code examples
javamultithreadingkeywordsynchronized

Why does using void keyword before synchronized throws an error in Java, but the reverse works fine?


import java.util.*;

public class Deadlock extends Thread{

    private String name;    

    public static void main(String[] args) {        

    }

    public class MyObject{
        public void synchronized foo(String name) { //throws error saying 'Syntax error on token "void", volatile expected' 

        }       
    }   
}

But if, public void synchronized is changed to public synchronized void, everything is fine.

Why is that?


Solution

  • Look at the Java Specification 8.4.3. Method modifiers which says:

    MethodModifier:
        (one of) 
        Annotation public protected private 
        abstract static final synchronized native strictfp
    

    Those must precede the return type, which comes as the last. The modifiers order does really not matter since they respect the return type comes as the last. That's why public synchronized void is valid.