Is a Java FileLock a POSIX advisory (fcntl) lock

前端 未结 2 1384
温柔的废话
温柔的废话 2021-01-14 08:30

I have a C++ program that locks files using POSIX advisory locks. That is, it uses the POSIX fcntl system call for lock operations. I want a Java program to interoperate wit

相关标签:
2条回答
  • 2021-01-14 09:10

    Try this:

    (1) Write a small java program that locks a file and sleeps (or otherwise stops executing).

    (2) cat /proc/locks

    (3) You'll see lines like the following:

    24: POSIX  ADVISORY  READ  1784 08:01:27384070 1073742826 1073742335
    25: FLOCK  ADVISORY  WRITE 815  00:0f:9772     0          EOF
    

    Identify your process ID from column 5. If column 2 is FLOCK then flock is being used. If it is POSIX then column 2 will be POSIX, indicating fcntl (or lockf which is build on top of fcntl) is being used.

    If java has to choose one or the other then POSIX would be the sensible choice as it supports record locking.

    0 讨论(0)
  • 2021-01-14 09:13

    Some Unix operating systems, including Linux, provide BSD-style (flock) locks, so it might be thought that Java FileLock could be implemented using BSD-style locks rather than POSIX locks. But that is not possible, because BSD-style locks are whole-file locks rather than record locks, and FileLock is a record lock: each lock is for a range of bytes in a file. Thus there is no real choice on a Unix system, and assuming that the implementation of FileLock uses POSIX fcntl locks is a safe assumption on a Unix operating system.

    The resulting FileLock locks might or might not interact with BSD-style locks. BSD-style locks can be implemented using POSIX locks (this was the case for Linux before version 2.0), or the operating system might have the two styles of locking interact (this is the case for FreeBSD). But in general that can not be guaranteed, and BSD-style locks and Java locks might be effectively invisible to each other (this is the case for any version of Linux you are likely to encounter).

    0 讨论(0)
提交回复
热议问题