yotamoo
yotamoo

Reputation: 5462

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 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

Answers (4)

Santosh
Santosh

Reputation: 17923

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.

Upvotes: 0

Sylar
Sylar

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

Grooveek
Grooveek

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

Mike Samuel
Mike Samuel

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

Related Questions