What is the best way to lock a file in a Java cluster

I have a cluster of servers running on JBoss. I need to update the file in safe mode. To be specific I need

  • lock file A - lock, if it is already locked, in a safe manner, so that if the JVM dies suddenly, there will be no broken locks. A 30 second timeout will be great.
  • read file A
  • change content
  • write the file in the temporary name A.tmp
  • delete source file A
  • rename A.tmp to the corresponding name A
  • unlock file A

When I look at java.nio.FileLock, it seems to be related to InputStream. I just need to block the abstract name. I do not need to block part of the file. I could create a lock file for this (separate from the data file) if this is the best choice. However, the highlight of my problem is that I need to get a lock before I read it, and then release the lock after updating the file. Please note that I am updating the file in such a way as to ensure that I will never have a partially recorded file in the file system. I need to write the whole file, and then rename it after it is written, to make sure that any file contains this name, has a full set of contents, and if the process dies during recording, it reserves a temporary file, which can be easily cleaned later.

java.nio.FileLock ? - ?

+4
1

. "XXX" "XXX # LOCK"

  • RandomAccessFile.

  • , : , , ..

:

    File lockFile = new File(target.getParent(), target.getName() + "#LOCK");
    lockAccessFile = new RandomAccessFile(lockFile, "rw");
    FileChannel lockChannel = lockAccessFile.getChannel();
    lock = lockChannel.lock();

:

    if (lock != null) {
        lock.release();
        lock = null;
    }
    if (lockAccessFile != null) {
        lockAccessFile.close();
        lockAccessFile = null;
    }

, . , lock lockAccessFile -.

, . (6 ), LOCK , , .

, - , . , - , , . , , Java. -, .

0

Source: https://habr.com/ru/post/1648784/


All Articles