4

I saw a Java example that had a main method labeled as synchronized, calling another static synchronized method. The effect is that, basically, the other method runs on the separate thread only after the main method has returned.

What practical functionality would such a construct have?

public class SynchronisedMain {

    public static synchronized void main(String[] args) throws InterruptedException {
        new Thread(new Runnable() {
            @Override
            public void run() {
                thingy();               
            }
        }).start();
        System.out.println("Kickstarted thingy thread.");
        TimeUnit.MILLISECONDS.sleep(1000);
    }

    public static synchronized void thingy() {
        System.out.println("Thingy!");
    }
}
Andrei Bârsan
  • 3,473
  • 2
  • 22
  • 46

2 Answers2

5

It's probably useful as a makeshift "application closed handler", doing some cleanup duty before the app finishes entirely. It's pretty contrived though...

Tudor
  • 61,523
  • 12
  • 102
  • 142
  • Certainly contrived. If this was "really" needed, pull that method into a new method with a different name. – tjg184 Jun 29 '12 at 12:48
3

There is nothing that says the main function can only be used as the entry point to a program. Being static, there is no reason other classes couldn't call SynchronisizedMain.main(). Being synchronized prevents multiple instances from being executed concurrently which might be desirable.

Colin D
  • 5,641
  • 1
  • 23
  • 35
  • But would this actually take place in practice? It could become confusing having various main methods get called throughout your program... – Andrei Bârsan Jun 29 '12 at 13:47
  • Usually if you are going to do this, you would expose the main method in a way that does not require it to reparse parameters you pass it. ie. WordCount.main(String [] args) would be WordCount.main(String fileName). If each main method is thought of as a subprogram or external program, there is a lot less confusion. – Colin D Jun 29 '12 at 14:03