Can I declare the main () method as synchronized to avoid the .jar file (consisting only of main ()) being executed twice at the same time?

I have the following information about the main method declaration .

So, reading this discussion: Declaring the main synchronization method

I can read that:

Synchronization prevents multiple instances from running at the same time, which might be desirable.

So what does this statement mean?

I am trying to make an example:

I have a very latch batch application that does some stuff in the database. This application consists mainly of a main () method . It is compiled into a .jar file that can be executed.

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

+3


source to share


3 answers


No, It is Immpossible. Synchronization only works when executing the same program. If you run the jar twice, it launches two different executions of the program, each with its own address space, they have no shared objects or memory.



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

+8


source


Synchronization is not possible in JVM diff 2 using the sync keyword. You can try something like



Preventing multiple instances of a Java application from running

+1


source


synchronized

will only allow one thread to own the lock on the object. This is primarily done to ensure data integrity.

Synchronization scope does not apply to multiple OS process

. Therefore, marking the main method as synchronized will not achieve the desired effect.

+1


source







All Articles