alessandroAmedei
alessandroAmedei

Reputation: 63

Thread Interruptded Exception, release semaphore resources

I have three threads and they need some resources to run (A,B,C) that I have implemented using Semaphores.

public void run(){
 while(!Thread.currentThread().isInterrupted){
  try{
    A.acquire(2);
    B.acquire(2);
    //some-stuff
  }
  catch(InterruptedException ex){}
  finally{ 
     A.release(2); //PROBLEM
     B.release(2);
         }
  }

Problem: while running, the thread could be interrupted but, going in the finally method I don't know where I was during the interruption so I don't know if I have to release something or not. I have tried a lot of different implementation, like using the method (boolean) tryAcquire() but another problem comes up: if I get the resource A but not the B, then in the finally block I would release the A again etc. Do you have any suggestions? Thank you.

Upvotes: 2

Views: 522

Answers (2)

Ivan
Ivan

Reputation: 8758

You could try to use List like this:

List<Semaphore> acquired = new ArrayList<>(2);
while(!Thread.currentThread().isInterrupted) { 
  try{
    A.acquire(2);
    acquired.add(A);
    B.acquire(2);
    acquired.add(B);
    //some-stuff
  } catch(InterruptedException ex){}
  finally{ 
    for (Semaphore s : acquired) {
      s.release(2);
    }
    s.clear();
  }
}

Upvotes: 0

shmosel
shmosel

Reputation: 50726

Use nested try blocks:

try {
    A.acquire(2);
    try {
        B.acquire(2);
        try {
            // some stuff
        } finally {
            B.release(2);
        }
    } finally {
        A.release(2);
    }
} catch (InterruptedException ex) {}

Upvotes: 1

Related Questions