This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
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 Android Security Essentials Live Lessons this week in the Android 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: 3023
    
  35

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.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: differences between Mutex and semaphores
 
Similar Threads
Thread states, notify, notifyAll, wait
NX: Data a singleton and no cache - trouble? Andrew help if you can
URLyBird 1.3.1: Locking Problem
How to Stop a Thread.......
Question with Habibi's Locking Example