Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I have a lock on a file when I want to delete it?

I have a bunch of files on a local file system. My server will serve those files. In some cases the server will receive an instruction to delete a file. At the moment I'm using FileChannel.lock() to acquire a lock on the file, this is mostly to make sure that some other process isn't editing the file when I try to delete it.
If I successfully acquire the lock, can I delete the file straight away, or do I need to release the lock first?
like this:

FileOutputStream out = new FileOutputStream(file);
FileChannel channel = out.getChannel();
FileLock lock = channel.lock();
if(lock.isValid() && !lock.isShared()){
    Path filePath = Paths.get(file.getPath());
    Files.delete(filePath);
}

Do I need to release the lock after I've deleted the file?

Or should it be like this (lock.release() added):

FileOutputStream out = new FileOutputStream(file);
FileChannel channel = out.getChannel();
FileLock lock = channel.lock();
if(lock.isValid() && !lock.isShared()){
    lock.release();
    Path filePath = Paths.get(file.getPath());
    Files.delete(filePath);
}

EDIT:
So it turns out the code above wouldn't work anyway, because you can't modify the file with a FileInputStream because, of course, it's read only. I've modified the code above to use FileOutputStream instead, but it still doesn't quite work, because even though I release the lock from the channel, the file object still has a lock. So I modified the code like so:

FileOutputStream out = new FileOutputStream(file);
                    FileChannel channel = out.getChannel();
                    FileLock lock = channel.lock();
                    if(lock.isValid() && !lock.isShared()){
                        channel.close();
                        boolean deleted = file.delete();
                        logger.info("{} @{} File {} deleted: {}", id, type, file.getName(), deleted);
                    }

This seems to work as expected. I'd still like to know if this is safe, or if there's a better way to do this?

like image 615
mal Avatar asked Nov 08 '22 00:11

mal


1 Answers

File lock wont work while deleting the file. File lock will work only while some other process wants to edit the same file. Before deleting the file , you need to release the lock and close the channel

like image 102
Nivedhitha N Avatar answered Nov 14 '22 22:11

Nivedhitha N