3

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?

Community
  • 1
  • 1
AndreaNobili
  • 40,955
  • 107
  • 324
  • 596
  • 1
    *I can't run 2 instance of this jar file at the same time?* This does not sounds right. If you are running the `jar` twice they will be separate JVMs. I would go for a lock file solution – Scary Wombat Apr 24 '17 at 07:52

3 Answers3

8

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.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
1

Synchronization is not possible in diff 2 JVMs using synchronized keyword. You can try something like

Prevent launching multiple instances of a java application

Community
  • 1
  • 1
Jaydeep Rajput
  • 3,605
  • 17
  • 35
1

synchronized will allow only one single thread to own a lock on an object. This is primarily done to maintain data integrity.

The scope of synchronized does not span across multiple OS process. Hence marking main method as synchronized, will not achieve the desired effect.

CuriousMind
  • 3,143
  • 3
  • 29
  • 54