Java Semaphore Stop Threads

Good afternoon everyone

I am working with Java semaphore and concurrency for a school project and have asked a few questions regarding how it works!

If there are no permissions available, I need a thread to exit the "queue" - not just sleep until it's ready. Is it possible? As you can see in mine try, catch, finally

- there is no descriptor for this event:

try {
    semaphore.acquire();
    System.out.println(Thread.currentThread().getName() + " aquired for 3 seconds " + semaphore.toString());
    Thread.sleep(3000);
}
catch (InterruptedException e) {
   e.printStackTrace();
} finally {   
   semaphore.release();
   System.out.println(Thread.currentThread().getName() + " released " + semaphore.toString());
}

      

Daniel brought up the function tryAquire

- it looks great, but the tutorials I've read indicate that semaphores require a block try, catch, finally

to prevent deadlocks. My current code (implementation tryAquire

) will be emitted in a block finally

, even if that stream was never received. Do you have any suggestions?

public void seatCustomer(int numBurritos) {
    try {
        if(semaphore.tryAcquire()) {
            System.out.println(Thread.currentThread().getName() + " aquired for 3 seconds " + semaphore.toString());
            Thread.sleep(3000); 
        } else {
            System.out.println(Thread.currentThread().getName() + " left due to full shop");
        }

    }
    catch (InterruptedException e) {
       e.printStackTrace();
    } finally {   
       semaphore.release();
       System.out.println(Thread.currentThread().getName() + " released " + semaphore.toString());
    }
}

      

+3


source to share


1 answer


I suggest you read the JavaDocs for Semaphor . In particular, take a look at the tryAcquire method.

Obtains permission from this semaphore only if it is available at the time of the call.

Gets a permission, if available, and returns immediately, with the value true, decreasing the number of available permissions by one.

If no permission is available, this method will return immediately with false.

This means that you can try to get permission if available. If none of these are available, this method returns false immediately instead of blocking.



You need to make your "final" block a little smarter.

boolean hasPermit = false;
try {
    hasPermit = semaphore.tryAcquire();
    if (hasPermit) {
        // do stuff.
    }
} finally {
    if (hasPermit) {
       semaphore.release();
    }
}

      

+4


source







All Articles