仅运行可执行 Jar 文件的单个实例

发布于 2024-12-28 03:21:17 字数 269 浏览 4 评论 0原文

所以我将我的项目打包为一个可以正常工作的可执行 jar。但有时,用户会多次启动该文件,这会导致它启动同一项目的多个实例(导致意外行为,例如,项目的延迟实例覆盖文件中的值)。

我想知道对于 Windows 平台(Win7),有哪些选项可以仅锁定一次执行,然后如果 jar 已经在运行,则不再继续执行代码。

我读到了有关进程ID的信息,但如果有多个java应用程序,它们最终都会将图像名称显示为javaw.exe,我如何确定自己的进程ID?

请建议做这件事的正确方法是什么,谢谢!

So i have packaged my project as a single executable jar that works fine. But at times it happens that the user launches the file multiple times, and this causes it to launch multiple instances of same project (causing unexpected behavior e.g overwriting values in files by delayed instances of project).

I want to know for a windows platform (Win7), what are the options to lock the execution for only one time, and then if the jar is already running, simply don't proceed executing the code again.

I read about Process ID's but if there are multiple java app's they all end up showing imagename as javaw.exe and how can i determine own process id??

Please suggest what is the proper way of doing this thing, thank you!!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

双手揣兜 2025-01-04 03:21:17

最简单的解决方案是使用固定的、未使用的端口。

ServerSocket ss;
try {
    ss = new ServerSocket(MY_PORT);
    // not already running.
} catch (BindException e) {
    // already running.
}

The simplest solution is to use a fixed, unused port.

ServerSocket ss;
try {
    ss = new ServerSocket(MY_PORT);
    // not already running.
} catch (BindException e) {
    // already running.
}
擦肩而过的背影 2025-01-04 03:21:17

根据我的经验,我使用的最佳方法是在特定端口(例如 61234)上创建侦听 ServerSocket。该套接字不执行任何操作,但如果您设法创建它,则意味着尚未启动其他进程。可执行 jar 文件的重复实例将无法在同一端口上创建 ServerSocket,因此它们应该退出。

Based on my experience, the best approach I used was to create a listening ServerSocket on a specific port (like 61234). The socket doesn't do anything, but if you manage to create it, it means that no other process has been started. The duplicated instances of the executable jar file will fail to create a ServerSocket on the same port and so they should exit.

他是夢罘是命 2025-01-04 03:21:17

您可以在应用程序启动时在专用 TCP 端口上打开 ServerSocket,并在应用程序关闭时将其关闭。

如果实例已在运行,您将收到“端口正在使用”异常。

You can open a ServerSocket on a dedicated TCP port at your application start-up, and close it at your application shutdown.

If an instance is already running, you'll get a "Port in use" exception.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文