Search code examples
javamultithreadingjava-threads

Can I declare the main() method as synchronized to avoid that a .jar file (composed by only a main()) is executed twice at the same time?


I have the following dount about declaring the main method synchronized.

So reading on this discussion: Declaring the main method synchronized

I can read that:

Being synchronized prevents multiple instances from being executed concurrently which might be desirable.

So what exactly means this assertion?

I try to do an example:

I have a very litle batch application that do some stuff on a database. This application is composed mainly from the main() method. It i compiled in a .jar file that can be executed.

It means that declaring this main() method as synchronized I can't run 2 instance of this jar file at the same time? Or am I missing something?


Solution

  • No, that is not possible. Synchronization only works within the same program execution. If you start a jar twice, it starts two different program executions, each with their own address space, they don't share any objects or memory.

    If you want to prevent multiple executions of the same program, you need to have something for external locking, for example a lock file.