简体   繁体   English

Java进程间互斥锁

[英]Java inter-process mutex

I need to implement some kind of inter-process mutex in Java.我需要在 Java 中实现某种进程间互斥锁。 I'm considering using the FileLock API as recommended in this thread .我正在考虑按照此线程中的建议使用 FileLock API。 I'll basically be using a dummy file and locking it in each process.我基本上会使用一个虚拟文件并在每个进程中锁定它。

Is this the best approach?这是最好的方法吗? Or is something like this built in the standard API (I can't find it).或者是在标准 API 中构建的类似内容(我找不到)。

For more details see below:有关更多详细信息,请参见下文:

I have written an application which reads some input files and updates some database tables according to what it finds in them (it's more complex, but business logic is irrelevant here).我编写了一个应用程序,它读取一些输入文件并根据它在其中找到的内容更新一些数据库表(它更复杂,但业务逻辑在这里无关紧要)。

I need to ensure mutual exclusion between multiple database updates.我需要确保多个数据库更新之间的互斥。 I tried to implement this with LOCK TABLE, but this is unsupported by the engine I'm using.我试图用 LOCK TABLE 来实现这个,但是我使用的引擎不支持它。 So, I want to implement the locking support in the application code.所以,我想在应用程序代码中实现锁定支持。

I went for the FileLock API approach and implemented a simple mutex based on:我采用了 FileLock API 方法并基于以下内容实现了一个简单的互斥锁:

All the processes use the same dummy file for acquiring locks.所有进程都使用相同的虚拟文件来获取锁。

Why bother using files, if you have database on your hands?如果您手上有数据库,为什么还要使用文件? Try using database locking like this ( https://dev.mysql.com/doc/refman/5.0/en/innodb-locking-reads.html ).尝试使用这样的数据库锁定( https://dev.mysql.com/doc/refman/5.0/en/innodb-locking-reads.html )。

By the way, what database engine do you use?顺便问一下,您使用什么数据库引擎? It might help if you list it.如果你列出它可能会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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