0

Are Mutexes and Semaphores much useful classes in Java keeping in mind that Synchronize utility has also been provided ? Or they have just been provided for sake of completeness as compared with C++? I do not find much coverage on Mutexes and Semaphores.

Ran N
  • 59
  • 6
  • 1
    possible duplicate of [Is there a Mutex in Java?](http://stackoverflow.com/questions/5291041/is-there-a-mutex-in-java) – Alon Aug 03 '15 at 12:10
  • possible duplicate of http://stackoverflow.com/questions/771347/what-is-mutex-and-semaphore-in-java-what-is-the-main-difference – Viktor Mellgren Aug 03 '15 at 12:15
  • The question asks for comparaison of semaphores/mutex against `synchronized`, whereas the proposed duplicates do not talk about synchronized. – GPI Aug 03 '15 at 12:26
  • Have a look at _Java Concurrency in Practice_. – Brian Goetz Aug 03 '15 at 14:29

1 Answers1

2

In multithreaded applications where data is either shared or tasks synchronized, the lowest level object in accomplishing this is the simple lock or mutex. On top of that you build more complicated objects or algorithms, like Semaphore.

Java has over the years provided the objects and algorithms for many of the most commons multithreaded design patterns. Take a look at the java.util.concurrent package for a complete list.

Synchronize, IMHO, I think replaces most use cases of the humble mutex. And it cuts down on lines of code in process. But there are still use cases for Semaphores. As you can see in the java.util.conccurrent package the Semaphore class was added in Java 1.5. So I think, and I think that the writers of Java also think, that there is still a need for the Semaphore object. But please take a look at the various classes provided in the java.util.concurrent package. Just reading through it provides insight into common multithreaded patterns that you may not have known beforehand. Using a more succinct concurrent Class to solve a multithreaded problem, versus implementing more complicated code using a lower level constructs (like a simple mutex or synchronized block) may lead to less lines of code and more elegant solution.

Jose Martinez
  • 11,452
  • 7
  • 53
  • 68
  • "Synchronize, IMHO, I think replaces most use cases of the humble mutex" -- thank you. But I just wonder at the people's judgement to my query, On one hand they upvote your informative answer but on the other do not appreciate the query that brought out that information. – Ran N Aug 03 '15 at 14:10
  • The people on here do not all think alike. Some of them are very picky about what is considered a good question or not. You just need to be brave when you ask or answer questions. In time your questions will get less down votes and more upvotes. – Jose Martinez Aug 03 '15 at 15:01