a-weinert / a-weinert.github.io

Albrecht's Blog (web content)
https://a-weinert.github.io/index.html
0 stars 0 forks source link

Java's incompatible file lock #5

Open a-weinert opened 5 years ago

a-weinert commented 5 years ago

Java's own file lock (by java.nio.channels.FileLock) is incompatible with Unux'/Linunux' flock(). You may comment thereto or to the blog post (German) here.

drm commented 3 years ago

Hi, I ran into your blog while searching for a C <-> Java compatible file locking solution. I've found you can use lockf (the POSIX advisory lock on top of fcntl) which Java internally uses on Linux as well.

I haven't tested this on MacOSX and I don't care about Windows in my case, but I thought you might be interested to know nonetheless.

edit: I created a little proof of concept to demonstrate: https://github.com/drm/java-filelock-respected-by-C

a-weinert commented 3 years ago

Thanks for trying this out. As I'm preparing an improved and generalised Pi IO with Java solution and a (print) publication thereon your comment could have come at no better time. Thanks. Getting my original Pi for "Raspberry Pi GPIO mit Java" (jaxenter.de/java/java-programmiersprache-c-raspberry-pi) back on and work there on base of your program.

The outcome so far: It is not Java's incompatible file lock – it's "At least two incompatible file locks in C". If you start the demo justHeld (based on your file, see weinert-automation.de/software/weAutRasp/) three times (pid 1315..1317) you can lock the same file twice and fail only from the third try on: justHeld.c (1315) lockf() /home/pi/bin/.lockPiGpio for 30 s justHeld.c (1316) lock by lockf() failed: Resource temporarily unavailable justHeld.c (1316) flock() /home/pi/bin/.lockPiGpio for 30 s justHeld.c (1317) lock by lockf() failed: Resource temporarily unavailable justHeld.c (1317) lock by flock() also failed: Resource temporarily unavailable justHeld.c (1315) lockf() /home/pi/bin/.lockPiGpio released after 30 s justHeld.c (1316) flock() /home/pi/bin/.lockPiGpio released after 30 s

Whatever the fine semantic differences an intentions of flock() vs lockf() for exotic and remote file systems might be, the getting two locks on one tiny local file on a simple machine is totally contradicting the idea (the semantics) of a file lock. I think this behaviour is a big bug of the historically later ones (fcntl, lockf).