简体   繁体   中英

How can i share the variable/block between two java process in same system?

Let's assume I have a Java program with a main class in persondetails.java .

Person1 runs persondetails.java to get their details. When a second person tries to access the same program in same system, it should say someone is already using this program, wait until the specific block completes in person1.

How can I communicate between these two Java processes in the same system?

If I understand your question correctly you would like to have a program that only allows one instance to be running at a time? I can think of two possibilities off the top of my head.

  • Using some kind of "lock" file on the filesystem. When the program is executed it could check for the existence of the lock file and display an error if it already exists. If the lock file doesn't exist it would be created and the program allowed to continue. You would just have to make sure you delete the lock file when the program finishes.

  • Binding to a specific port (that is unlikely to already being used). When the program is executed you would attempt to bind to the port, if you can the program continues otherwise you give an error.

Either way you are just using a locking mechanism to detect that the other process is running.

Locking using the file system can be problematic. For example if the program fails and stops executing unexpectedly the lock file could remain and prevent future execution of the program. At the same time binding to a port to accomplish this is really a misuse of that functionality and could be problematic in it's own way (port already in use, or the application not being allowed to bind to the port).

I personally would be carefully considering whether or not it is really necessary to do this kind of locking between different processes. I would consider it favorable to avoid using either of the options I mentioned previously.

At a very very basic level, the program could create a file named lock. The process would be something like

  1. Process A checks for existence of lock.
  2. If lock does not exist, Process A creates lock and begins to work.
    1. At the end of work, Process A deletes lock.
  3. If lock exists, Process A waits until lock does not exist.
    1. Process A can poll or wait for an interrupt or any of a variety of callback mechanisms.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM