What is mutex and semaphore in Java ? What is the main difference ?
Semaphore:
A counting semaphore. Conceptually, a semaphore maintains a set of permits. Each
acquire()blocks if necessary until a permit is available, and then takes it. Eachrelease()adds a permit, potentially releasing a blocking acquirer. However, no actual permit objects are used; the Semaphore just keeps a count of the number available and acts accordingly.
Semaphores are often used to restrict the number of threads than can access some (physical or logical) resource
Java does not have built-in Mutex API. But it can be implemented as binary semaphore.
A semaphore initialized to one, and which is used such that it only has at most one permit available, can serve as a mutual exclusion lock. This is more commonly known as a binary semaphore, because it only has two states: one permit available, or zero permits available.
When used in this way, the binary semaphore has the property (unlike many Lock implementations), that the "lock" can be released by a thread other than the owner (as semaphores have no notion of ownership). This can be useful in some specialized contexts, such as deadlock recovery.
So key differences between Semaphore and Mutex:
Semaphore restrict number of threads to access a resource throuhg permits. Mutex allows only one thread to access resource.
No threads owns Semaphore. Threads can update number of permits by calling acquire() and release() methods. Mutexes should be unlocked only by the thread holding the lock.
When a mutex is used with condition variables, there is an implied bracketing—it is clear which part of the program is being protected. This is not necessarily the case for a semaphore, which might be called the go to of concurrent programming—it is powerful but too easy to use in an unstructured, indeterminate way.