简体   繁体   English

我们如何确保即使在2个不同的JVM中也只运行任何应用程序的一个实例

[英]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.

相关问题 如何确保只有一个 Java 应用程序实例正在运行? - How to make sure that only a single instance of a Java application is running? 如何确保JVM中只有一个类实例? - How to make sure that there is just one instance of class in JVM? 我们如何确保我们只能创建一个类的实例? - How can we make sure that we can just create one instance of a class? 我们如何确保在任何时间仅调用类的静态方法和非静态方法之一? - How can we make sure that at any point of time only one of a static method & a non-static method of a class gets called? JVM如何确保只有一个线程可以获取对象的锁? - How does JVM make sure only one thread can acquire the lock of an object? 如何确保只能执行我的程序的一个实例? - How do I make sure only one instance of my program can be executed? 如何确保一次只调用一个servlet(不是实例)? - how to I make sure that only one servlet(not instance) is call at a time? 如何确保每个 jvm 有一个 guava 服务管理器实例? - how to make sure single guava service manager instance per jvm? 如何从一个JVM进程获取有关不同的Java进程(另一个运行不同进程的JVM实例)的信息? - How to get information about a different java process (another JVM instance running different processes) from one JVM process? 没有检测到本地JVM,甚至没有运行Java任务控制实例的jvm - No local JVM's were detected, not even the jvm running this instance of java mission control
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM