Difference between Semaphore and Condition (Reentr

2020-02-29 23:08发布

问题:

Does anyone know the differences between the methods acquire () and release () (java.util.concurrent.Semaphore) and await () and signal (new ReentrantLock().newCondition() ) .

Can you expose a pseudo code for each of these methods?

回答1:

Superficially the behavior of these method might look similar - acquire()/await() can make threads block in some cirsumstances and release()/signal() can unblock threads in some circumstances. However Semaphore and Condition serve different purposes:

  • java.util.concurrent.Semaphore is relatively higher-level synchronization mechanism, intended for use by general developers. You would use it typically to restrict concurrent access to some resource by making each requester thread call acquire() before accessing the resource (that way making the thread block if no semaphore permit was available). Description from the javadoc:

    Conceptually, a semaphore maintains a set of permits. Each acquire() blocks if necessary until a permit is available, and then takes it. Each release() adds a permit, potentially releasing a blocking acquirer.

  • java.util.concurrent.locks.Condition is relatively low-level synchronization mechanism which basically enhances functionality provided java.lang.Object methods wait(), notify() and notifyAll(). It enables the thread to suspend its activities when it needs to wait for some condition to become true (generally through activity of other threads) and then it enables those other threads to "wake up" the waiting thread(s) when the state variables taking part in the condition might have changed. It is generally harder to use correctly and general developers are advised to use higher-level mechanisms from package java.util.concurrent (like Semaphore).

You can find more detailed information about this in the excellent book "Java Concurrency in Practice" from Brian Goetz.