Java File Locking

随声附和 提交于 2019-11-30 18:00:00
AndiDog

If the file is only accessed from your program, the synchronized lock object is okay. But if you want to protect the file from being changed by other programs while you're working on it, you can use Java's file locking features in java.nio.channels.FileLock (example). As the text says, mind that on some operating systems, programs can still change files if they don't check for an existing file lock.

Instead of sharing a lock, maybe you could have a separate process that was responsible for maintaining a lock on the file. To begin your read/modify/write step, a Thread would have to ask this central process for the lock via HTTP, or messaging, or whatever you like. If the request is denied, the Thread would go to sleep, wake up, and try again. Otherwise the Thread would read/modify/write and then tell the locking process that it is releasing the lock.

You'll want to synchronize on some object. For example:

synchronized(fileLockObject) {
    readContentsFromFile(f);
    modifyContentsFromFile(f);
    writeFile(f);
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!