Multiple java programs write a file, how to ensure that only one program is writing this file?

what we used to do is to add multi-thread locking. In fact, we only need to add a synchronized, but how can we ensure that only one process is writing if there are several different java programs?

is it okay to use a file lock?

 FileChannel fc = fi.getChannel(); 
    return fc.tryLock(); 

if you leave it alone, will it be a problem for multiple processes to write a file at the same time?

Feb.14,2022

what we used to do is to add multi-thread locks. In fact, we only need to add a synchronized, but how can we ensure that only one process is writing if there are several different java programs?

locking multiple different applications requires a common middleware to control the lock, such as Redis, Zookeeper, and database.

as long as exclusivity can be achieved, files are similar; as long as they can be exclusive.

here is a Redis-based distributed lock that you can learn about; the ideas are all the same.

https://github.com/crossoverJ.

https://crossoverjie.top/tags.


whether multiple processes write the same file or multiple threads write the same fast memory, it is a problem of competition for shared resources. if left unchecked, the operating system will write all your content to the hard disk without reporting any errors. but this will cause uncertainty in the results of the program, or the results of unpredictable programs, which will lead to other problems. So there are a series of Synchronize schemes to avoid this uncertainty, such as semaphores, locks and so on. If you can tolerate this uncertainty, just let it go.

in addition, java provides a file locking mechanism, and multiple jvm processes are still feasible. If you call the lock and tryLock methods of the FileChannel class, the first call will block until the lock can be obtained, and the second call will return immediately, either returning the lock or null if the lock is not available. The file will remain locked until the channel is closed or the release method is called on the lock.

these two methods can also add locks on an area of the file, as shown in API.

There seems to be no concept of file locks in

linux, but there are file locks in windows. Personally, I feel that the need to modify files in smaller projects can be used to control the number of changes through background code and page prompts.

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b40998-2ba72.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b40998-2ba72.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?