File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "differences between Mutex and semaphores" Watch "differences between Mutex and semaphores" New topic
Author

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,
Oleg.
Devaka Cooray
ExamLab Creator
Saloon Keeper

Joined: Jul 29, 2008
Posts: 3060
    
  38

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
author
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: http://aspose.com/file-tools
 
subject: differences between Mutex and semaphores