Saturday, April 17, 2010

What is the difference between mutex, monitor, lock and semaphore?

Mutex is a lock. At any point of time only one thread can hold that lock and once its job is done, it has to acknowledge that through unlocking mechanism. Its used for mutual exclusion to avoid multiple threads corrupting global datasource. Java's synchronized keyword does this internally.

Semaphores are useful in sharing common resources efficiently through counters. For example object pooling and thread pooling can be implemented through counting semaphores. By functionality binary semaphore is equivalent to mutex except the fact that monitor ownership is provided in the mutex case. In java, semaphores can be implemented through wait and notify mechanism.

Lock shall be implemented using Monitor.  Monitor and Lock are giving same functionality. Across threads mutual exclusion can be implemented using Monitors. Across processes mutual exclusion can be implemented using mutex.

1 comment:

  1. for example java.util.concurrent.Semaphore has methods as acquire() and release() which means it has no reference to which object has been released.

    ReplyDelete