Java inter-process mutex

2019-02-26 03:39发布

问题:

I need to implement some kind of inter-process mutex in Java. I'm considering using the FileLock API as recommended in this thread. 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).

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. So, I want to implement the locking support in the application code.

回答1:

I went for the FileLock API approach and implemented a simple mutex based on:

  • FileChannel.lock
  • FileLock.release

All the processes use the same dummy file for acquiring locks.



回答2:

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).

By the way, what database engine do you use? It might help if you list it.