Reputation: 5462
Hi there I'm building a little p2p program, so I want to make a file unable to be deleted while it is being downloaded. The simple solution is to use a lock, but then again I want it to be possible for multiple clients to download the file (meaning many thread can access the download method at the same time). I hope the situation is clear. any ideas of how to implement it? Thanks!
Upvotes: 0
Views: 170
Reputation: 17923
I have a programmatic solution for this problem
Problem with this approach : If a thread crashes due to some reason or the other, stack will always have an entry and that file will never get deleted.
Upvotes: 0
Reputation: 2333
Make use of java.util.concurrent.locks.ReentrantReadWriteLock. Use a java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock fot the thread that is downloading the file and java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock for the other threads that should access it while it its being downloaded.
Upvotes: 1
Reputation: 10094
You can't handle the case when the deletion comes from a system call, that's unfortunately impossible in java
So either you cope with that and you guard your 'delete' method by a simple FileLockManager or whatever, or given the size of the file is small, you can copy it to another directory (1 temporary file per client/group of client for example) then the user can do whatever he wants with the original file
just my 2 cents
Upvotes: 0
Reputation: 120586
There's a bunch of lock implementations at http://download.java.net/jdk7/docs/api/java/util/concurrent/locks/package-frame.html which should help if all possible deleters are in the same VM, but there's no flock equivalent in the java core libraries.
Upvotes: 0