1/24
Name | Mastery | Learn | Test | Matching | Spaced |
---|
No study sessions yet.
What is a Semaphore in Java?
A concurrency utility that controls access to a resource by multiple threads using permits.
Which package includes Semaphore?
java.util.concurrent
What is the main purpose of Semaphore?
To limit the number of threads accessing a resource simultaneously.
How do you create a Semaphore with 3 permits?
new Semaphore(3)
What does acquire()
do in Semaphore?
It acquires a permit, blocking if necessary until one becomes available.
What does release()
do in Semaphore?
It releases a permit, increasing the number of available permits.
What happens if no permits are available in Semaphore?
Calling thread blocks until a permit is released.
What is a fair semaphore?
A semaphore that grants permits in the order of thread requests (FIFO).
How do you create a fair Semaphore?
new Semaphore(permits, true)
What is the difference between fair and non-fair Semaphore?
Fair ensures FIFO granting of permits; non-fair may grant out of order.
What method checks the number of available permits?
availablePermits()
What method attempts to acquire a permit without blocking?
tryAcquire()
How can you acquire multiple permits at once?
Using acquire(int permits)
or tryAcquire(int permits)
Can acquire()
be interrupted?
Yes, it throws InterruptedException
if the thread is interrupted while waiting.
What happens if a thread calls release()
without acquire()
?
Permit count increases, possibly beyond initial permits (not recommended).
Is Semaphore reusable?
Yes, permits can be repeatedly acquired and released.
What is a real-world use case for Semaphore?
Controlling access to a limited number of connections in a connection pool.
What is the difference between Semaphore and Lock?
Semaphore controls number of threads accessing; Lock provides exclusive locking.
What is the difference between Semaphore and CountDownLatch?
Semaphore is reusable and dynamic; CountDownLatch is one-time and countdown only.
Can you use Semaphore to implement a mutex?
Yes, by creating a Semaphore with one permit.
Is release()
method safe to call in finally block?
Yes, it's a best practice to release permits in a finally
block.
What happens if a thread acquires more permits than available?
It blocks until enough permits are released by other threads.
Can a Semaphore be used for signaling between threads?
Not ideal; use CountDownLatch
or Exchanger
for better signaling mechanisms.
What are the key methods of Semaphore?
acquire()
, release()
, tryAcquire()
, availablePermits()
, drainPermits()
What does drainPermits()
do?
Removes and returns all available permits immediately.