File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

differences between Mutex and semaphores

 
Oleg Tikhonov
Ranch Hand
Posts: 55
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Sergey,

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

Thank you in advance,
Oleg.
 
Devaka Cooray
ExamLab Creator
Marshal
Pie
Posts: 4116
195
Chrome Eclipse IDE Google App Engine IntelliJ IDE jQuery Postgres Database Tomcat Server
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Sergey Babkin
author
Ranch Hand
Posts: 50
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic