0

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!

4 Answers 4

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

but i see that using this lock only one thread gains access to the lock, how can i make it accessible to many threads?
The trick is to pause the download in intervals, releasing the writelock for a short time. This enables all waiting readlocks to access the so far downloaded data in parallel. Then re-acquire the writelock and continue the download.. It is important that all read- and writelocks are acquired from the same ReadWriteLock instance.
ReadLocks do not block each other, they can access the locked area concurrently (if there is no WriteLock active)
0

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.

Comments

0

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

Comments

0

I have a programmatic solution for this problem

  1. Keep a stack data structure for each file. Keep this synchronized.
  2. 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.
  3. 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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.