1

i access some files kept on server using my application. Multiple users can login into the application, i want to put some explicit lock on files that is opened by 1 of the user and want to release the lock when user either logs out or stop using the file.

Any help how to do it?

Thanks in advance

Varun
  • 5,001
  • 12
  • 54
  • 85
  • 4
    http://stackoverflow.com/questions/128038/how-can-i-lock-a-file-using-java-if-possible – jmj Jan 03 '11 at 09:42
  • Gone through it ... what in case a person who applied the lock doesnt release the lock? – Varun Jan 03 '11 at 09:55

3 Answers3

1

you can try this:

try {
    // Get a file channel for the file
    File file = new File("filename");
    FileChannel channel = new RandomAccessFile(file, "rw").getChannel();

    // Use the file channel to create a lock on the file.
    // This method blocks until it can retrieve the lock.
    FileLock lock = channel.lock();

    // Try acquiring the lock without blocking. This method returns
    // null or throws an exception if the file is already locked.
    try {
        lock = channel.tryLock();
    } catch (OverlappingFileLockException e) {
        // File is already locked in this thread or virtual machine
    }

    // Release the lock
    lock.release();

    // Close the file
    channel.close();
} catch (Exception e) {
}

Hope this will help you

moinudin
  • 134,091
  • 45
  • 190
  • 216
UVM
  • 9,776
  • 6
  • 41
  • 66
  • @ UNNI - wat in case of some1 doesnt reach lock.release() will the file be released i mean what if users session expires or he closes the browser what in those cases? – Varun Jan 03 '11 at 10:03
  • The scenario I think you are talking about is the file has been already locked by x user.In that case lock.release will not be executed because it will throw the exception. Now talking about session scope is how you want to relate this file handling mechanism while the user is in session scope.I think you put a lock for the file only if the user is valid and put into session.In other scanrio, this piece of code may not execute.This descision is based on your design.Third thing is when the user closed the browser then you can trap the event using javascript and send server side comand foraction – UVM Jan 03 '11 at 10:53
0

You can try using FileLock. They can be difficult to get right but it may be your only choice.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

Are you using a database? Why not having a table that lists the files locked by a user? You can then acquire and release locks by inserting/deleting a row.

Don't forget an admin interface to release locks that have been incorrectly kept. Also consider implementing a kind of timeout (i.e. a lock is not valid anymore after XX hours)

Vincent Mimoun-Prat
  • 28,208
  • 16
  • 81
  • 124