Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens to a Thread that fails to acquire a Semaphore?

What happens when a thread cannot acquire a Semaphore (due to lack of permit). Will it be moved to the wait state?

EDIT:Will the thread start resume the previous execution sequence, when the semaphore becomes available.

like image 970
blitzkriegz Avatar asked Oct 21 '10 08:10

blitzkriegz


1 Answers

What happens when a thread cannot acquire a Semaphore (due to lack of permit). Will it be moved to the wait state?

Yes. If you're talking about java.util.concurrent.Semaphore (and the aquire method this is what happens:

Acquires a permit from this semaphore, blocking until one is available, or the thread is interrupted.

[...]

If no permit is available then the current thread becomes disabled for thread scheduling purposes and lies dormant until one of two things happens:

  • Some other thread invokes the release() method for this semaphore and the current thread is next to be assigned a permit; or

  • Some other thread interrupts the current thread.

tryAquire will however, as the name suggests, only try to aquire the lock, and instead of blocking return false if it has no permit.

Will the thread start resume the previous execution sequence, when the semaphore becomes available.

Yes. If another thread calls release this thread may return from acquire and continue it's execution.

like image 53
aioobe Avatar answered Oct 20 '22 22:10

aioobe