File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Threads and Synchronization and the fly likes differences between Mutex and semaphores Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "differences between Mutex and semaphores" Watch "differences between Mutex and semaphores" New topic

differences between Mutex and semaphores

Oleg Tikhonov
Ranch Hand

Joined: Aug 02, 2008
Posts: 55
Hello Sergey,

I'm wondering what are the difference(s) between mutex and semaphore ?

Thank you in advance,
Devaka Cooray
ExamLab Creator

Joined: Jul 29, 2008
Posts: 3927

Mutex avoid any concurrent access on a given block. When a thread owned the monitor lock of an object, another thread cannot own the monitor lock of that same object until the first thread releases the monitor lock.

Using Semaphore approach, you can let multiple threads to concurrently execute the business, while the maximum number of threads which can perform the simultaneous execution is limited. For an example, if we limit the maximum number of threads to 100, only 100 threads can execute the business at same time. Another thread willing to execute at the same time would have to stay in queue until one of the thread stops the execution - that limits the simultaneous access for 100 threads. Have a look at the documentation of java.util.concurrent.Semaphore class.

Author of ExamLab ExamLab - a free SCJP / OCPJP exam simulator
What would SCJP exam questions look like? -- Home -- Twitter -- How to Ask a Question
Sergey Babkin
Ranch Hand

Joined: Apr 05, 2010
Posts: 50
What Devaka says :-)

Actually, there are different kinds of semaphores. The ones that Dijkstra originally invented can count only to 1, and as such aren't really different from a mutex. The whole word comes from the railroad analogy, with multple trains wanting to go on the same track. The semaphore makes sure that only one train at a time goes there.

Currently the two main differences are that the semaphores can count to more than 1, and that mutexes are usually implemented as a more low-level primitive, and because of this are optimized for quick grab, do and release while semaphores are more sutiable for the long waits.
I agree. Here's the link:
subject: differences between Mutex and semaphores
It's not a secret anymore!