Java file locking mechanism for file based process communication

后端 未结 2 2040
难免孤独
难免孤独 2021-01-15 04:56

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 ther

2条回答
  •  长情又很酷
    2021-01-15 05:14

    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();
    }
    

提交回复
热议问题