[英]How can we make sure that only one instance of any application in running even in 2 different JVM's
I was asked this question at an interview. 我在接受采访时被问到这个问题。 Lets say VLC player is there and running on our OS. 让我们说VLC播放器在我们的操作系统上运行。 Now when we again try to launch VLC , that should not happen. 现在,当我们再次尝试启动VLC时,这不应该发生。
alternatively, say we have two command windows, we runn same java program in two different Windows. 或者,假设我们有两个命令窗口,我们在两个不同的Windows中运行相同的java程序。 How can we ensure only one runs. 我们怎样才能确保只有一次运行。
Is this OS dependent thing? 这是OS依赖的吗? Whats implementation? 什么是实施?
I read something about MUTEX/Semaphore but I guess that is inside one JVM only. 我读了一些关于MUTEX / Semaphore的内容,但我想这只是在一个JVM中。
You could write a pid file to disk, in a known location, indicating that the application is already running. 您可以将pid文件写入已知位置的磁盘,指示应用程序已在运行。 Then, on startup, look for that file. 然后,在启动时,查找该文件。 If it's there, the application is already running, so exit. 如果它在那里,应用程序已经运行,所以退出。
Left as an exercise to the reader: ensuring that the pid file is removed even when the app crashes. 作为练习留给读者:确保即使应用程序崩溃也删除了pid文件。
One possible answer would be to open and listen on a specific (and uncommon) tcp server port on start-up, since only one process can hold the socket at a time a second instance could detect the socket can't be listen'd and then exit with an error. 一个可能的答案是在启动时打开并侦听特定(且不常见)的tcp服务器端口,因为只有一个进程可以在第二个实例可以检测到套接字无法侦听的情况下保持套接字。然后退出并出错。 Alternatively, you could potentially create a File
on startup (and exit if it exists). 或者,您可以在启动时创建File
(如果存在则退出)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.