Java中的跨进程同步
如何同步 Windows 上运行的两个 Java 进程?
我正在寻找类似 Win32 命名互斥对象的东西,它允许两个进程使用相同的锁定对象。
谢谢
How can I synchornize two Java processes running on Windows ?
I am looking for something like the Win32 Named Mutex object which allows two processes to use the same locking object.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
Java跨进程锁:
Java cross process lock:
我简化了 Java42 答案
用法
successLockRunnable 中的代码将使用以下命令锁定同一台计算机上的任何其他进程这个实施。
来源
I simplified Java42 answer
Usage
The code in successLockRunnable will lock any other process on the same machine using this implementation.
Source
在 Java 中不可能做你想做的事情。不同的 Java 应用程序将使用不同的 JVM,将自己完全分成不同的“黑匣子”。但是,您有 2 个选择:
It is not possible to do something like you want in Java. Different Java applications will use different JVM's fully separating themselves into different 'blackbox'es. However, you have 2 options:
我们使用这些类型的语句来确保只有一个进程可以执行由“myLockKey”键入的代码块:
在这里,我们使用此类:
We use these kinds of statements to make sure only one process can do a block of code keyed by "myLockKey":
Here, we make use of this class:
我认为 java 平台中没有为此提供的本机方法。但是,有多种方法可以获得相同类型的效果,具体取决于您想要完成的同步。除了让进程通过网络连接(直接套接字、带有选举的多播等)进行通信或放弃平台特定的调用之外,您还可以探索获取共享文件的文件锁(请参阅 activemq 被动备用)例如,共享文件系统)或使用数据库以及诸如选择更新或表行的乐观更新之类的东西。
I don't think there are native methods in the java platform for this. However, there are several ways to go about obtaining the same type of effect depending on what synchronization you are trying to accomplish. In addition to having the processes communicate over network connections (direct sockets, multicast with an election, etc.) or dropping to platform specific calls, you can also explore obtaining a file lock to a shared file (see activemq passive stand-by with a shared file system for an example) or using a database either with something like a select for update or an optimistic update of a table row.
不确定您要做什么,我可能会通过 JMX 公开某些内容并让单独的进程设置一个状态标志,然后以编程方式将您的线程从等待状态恢复。当然,您可以使用套接字/RMI 来代替 JMX。
Not sure what you are trying to do, I'd possibly do this by exposing something via JMX and having the separate processes set a status flag which then programmatically revives your thread from a wait state. Instead of JMX you could of course use a socket/RMI.
使用套接字进行跨进程同步是常见的做法。不仅适用于 java 应用程序,因为在大多数 *nix 环境中,我们没有像 Windows 中那样的系统范围互斥锁。
using sockets for cross processes synchronizations is common practice . not only for java applications because in most *nix environments we have not system-wide mutexes as we have in Windows.