I am new to Java concurrency/multi-threading. Can somebody please explain to me in what situations the acquire() and acquireUninterruptibly() must (or must not) be used, how they are different; and also how to use them (code sample?).
Thank you very much.
Method SummaryAcquires a permit from this semaphore, blocking until one is available, or the thread is interrupted. Acquires the given number of permits from this semaphore, blocking until all are available, or the thread is interrupted.
Semaphore class is a counting semaphore. That means that it has two main methods: acquire() release()
Methods of Semaphore Class. Acquires the given number of permits, if they are available, and returns immediately, reducing the number of available permits by the given amount. If the current thread is interrupted while waiting for a permit then InterruptedException is thrown.
Semaphore is used to restrict the number of threads that can access a resource. That is, while synchronized allows only one thread to aquire lock and execute the synchonized block / method, Semaphore gives permission up to n threads to go and blocks the others.
Even though previous answers are technically correct i'd like to point out the following:
If you are using Semaphore
for transaction coordination between threads you may want to use acquireUninterruptibly()
to complete you transaction ad clean exit your process when the transaction (somehow) cleanly finish by testing thread interrupted state (you will know that the thread may have been interrupted after the call).
If you can handle InterruptedException
and immediately exit transaction without the need of any further operation you can use acquire()
.
Think you are waiting for a shared resource (a counter for example) to complete your transaction, if using acquire()
and ignoring the exception you may get the wrong resource state (a non unique counter in this case), so you may still want to wait for the resource and check later what to do based on the thread state. If, for example, you are doing a batch of transactions you may want to complete the current one and skip the subsequents.
acquire()
is interruptible. That means if a thread A is calling acquire()
on a semaphore, and thread B interrupts threads A by calling interrupt()
, then an InterruptedException
will be thrown on thread A.
On the other hand acquireUninterruptibly()
is not interruptible. That means if a thread A is calling acquireUninterruptibly()
on a semaphore, and thread B interrupts threads A by calling interrupt()
, then no InterruptedException
will be thrown on thread A, just that thread A will have its interrupted status set after acquireUninterruptibly()
returns.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With