using a lock in java
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 man开发者_高级运维y thread can access the download method at the same time). I hope the situation is clear. any ideas of how to implement it? Thanks!
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.
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.
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
I have a programmatic solution for this problem
- Keep a stack data structure for each file. Keep this synchronized.
- Whenever a thread is invoked for downloading a file, it will push an element in the stack and when its finished it will pop the element.
- Now the delete request for a particular file comes, it will always check the stack size and it succeeds only when the stack size is zero.
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.
精彩评论