Java file locking mechanism for file based process communication

拟墨画扇 提交于 2019-12-01 12:16:20

问题


I have two java process (JAR) one is writing to a text file on every 1 min and another is reading that file and call a web service to store data in database.

Is there any way to lock the file when it is on write mode? I have observed that when wvdial is dialing a modem its create a lock file in /var/lock/ttyUSB0..LOCK I think. I want a this kind of procedure if the file is on write mode the another process could wait till write done. After writing the process can read the file content.

Please guide me to solve my issue.

Thank you


回答1:


Maybe this class can help you http://docs.oracle.com/javase/7/docs/api/java/nio/channels/FileLock.html

Edit: This post might already be covering the subject How can I lock a file using java (if possible)

Exemple:

FileInputStream in = new FileInputStream(file);
try
{
    java.nio.channels.FileLock lock = in.getChannel().lock();
    try
    {
        //write
    }
    finally
    {
        lock.release();
    }
}
finally 
{
    in.close();
}

Now in the reading process:

FileInputStream in = new FileInputStream(file);
try
{
    FileLock lock = in.getChannel().tryLock();
    if (lock == null)
    {
        //file is locked, wait or do something else
    }
    else
    {
        try
        {
            //read
        }
        finally
        {
            lock.release();
        }
    }
}
finally 
{
    in.close();
}



回答2:


The problem you will have here is that Java cannot open() with O_EXCL, as a result you cannot create a file atomically.

Use a directory instead: creating a directory is an atomic operation. File's .mkdir() will return false if the directory cannot be created. rmdir() it when you're done.

Of course, make sure that both of your processes have write access to the base directory!



来源:https://stackoverflow.com/questions/16788740/java-file-locking-mechanism-for-file-based-process-communication

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