Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring the main method synchronized

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!");
    }
}
like image 411
Andrei Bârsan Avatar asked Feb 20 '23 00:02

Andrei Bârsan


1 Answers

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

like image 178
Tudor Avatar answered Feb 22 '23 14:02

Tudor