What is mutex and semaphore in Java ? What is the main difference?

105,734

Solution 1

Semaphore can be counted, while mutex can only count to 1.

Suppose you have a thread running which accepts client connections. This thread can handle 10 clients simultaneously. Then each new client sets the semaphore until it reaches 10. When the Semaphore has 10 flags, then your thread won't accept new connections

Mutex are usually used for guarding stuff. Suppose your 10 clients can access multiple parts of the system. Then you can protect a part of the system with a mutex so when 1 client is connected to that sub-system, no one else should have access. You can use a Semaphore for this purpose too. A mutex is a "Mutual Exclusion Semaphore".

Solution 2

Unfortunately everyone has missed the most important difference between the semaphore and the mutex; the concept of "ownership".

Semaphores have no notion of ownership, this means that any thread can release a semaphore (this can lead to many problems in itself but can help with "death detection"). Whereas a mutex does have the concept of ownership (i.e. you can only release a mutex you have acquired).
Ownership is incredibly important for safe programming of concurrent systems. I would always recommend using mutex in preference to a semaphore (but there are performance implications).

Mutexes also may support priority inheritance (which can help with the priority inversion problem) and recursion (eliminating one type of deadlock).

It should also be pointed out that there are "binary" semaphores and "counting/general" semaphores. Java's semaphore is a counting semaphore and thus allows it to be initialized with a value greater than one (whereas, as pointed out, a mutex can only a conceptual count of one). The usefulness of this has been pointed out in other posts.

So to summarize, unless you have multiple resources to manage, I would always recommend the mutex over the semaphore.

Solution 3

Mutex is basically mutual exclusion. Only one thread can acquire the resource at once. When one thread acquires the resource, no other thread is allowed to acquire the resource until the thread owning the resource releases. All threads waiting for acquiring resource would be blocked.

Semaphore is used to control the number of threads executing. There will be fixed set of resources. The resource count will gets decremented every time when a thread owns the same. When the semaphore count reaches 0 then no other threads are allowed to acquire the resource. The threads get blocked till other threads owning resource releases.

In short, the main difference is how many threads are allowed to acquire the resource at once ?

  • Mutex --its ONE.
  • Semaphore -- its DEFINED_COUNT, ( as many as semaphore count)

Solution 4

A mutex is used for serial access to a resource while a semaphore limits access to a resource up to a set number. You can think of a mutex as a semaphore with an access count of 1. Whatever you set your semaphore count to, that may threads can access the resource before the resource is blocked.

Solution 5

A mutex is often known as a binary semaphore. Whilst a semaphore can be created with any non-zero count a mutex is conceptually a semeaphore with an upper count of 1.

Share:
105,734

Related videos on Youtube

Isabel Jinson
Author by

Isabel Jinson

Updated on July 08, 2022

Comments

  • Isabel Jinson
    Isabel Jinson almost 2 years

    What is mutex and semaphore in Java ? What is the main difference ?

  • Saurabh
    Saurabh over 14 years
    This is not quite true. The same thread can enter the same mutex more than once, so a count needs to be maintained to ensure entries `& exits are balanced.
  • andrew pate
    andrew pate about 13 years
    Feabhas's answer is quite important - the mutex checks the thread attempting to release the mutex actually owns it. I've had this as an interview question so its worth trying to remember it.
  • edA-qa mort-ora-y
    edA-qa mort-ora-y about 13 years
    @finnw, in general there are two types of mutexes, recursive and non-recursive. Does Java by default use the recursive type?
  • Saurabh
    Saurabh about 13 years
    @edA-qa mort-ora-y, the term "Mutex" is not used in the Java VM or API spec so I am assuming it refers to the monitor built into every object, which is also similar to the Win32 object called a Mutex. The same applies to a ReentrantLock. All of these are recursive. I am not aware of any "real-world" examples of non-recursive mutexes (I have seen them only in textbooks) so I did not consider them.
  • Alexander Torstling
    Alexander Torstling over 12 years
    Non-recursive mutexes can be implemented by using a Semaphore with count one. This can be useful if you want to prevent recursive calls. This has practical uses, I've personally used it in big projects to detect loops in initialization code (A initializes B which tries to initialize A again).
  • Aditya Kumar Pandey
    Aditya Kumar Pandey over 11 years
    In C++11 (C++0x) standard, mutex is non-recursive. They also provide a separate 'recursive_mutex' for those that need that. I know we are talking Java here, but then many of us code across languages now.
  • Persixty
    Persixty almost 7 years
    I'm just going to pitch in that I think trying to describe a mutex as a special case of semaphore is generally unhelpful to beginners. Yes, a mutex can be implemented as a semaphore with the additional constraint that permits are non-transferable and the thread that acquired it must return it but they're far easier to conceptualise as a lock.
  • cmhteixeira
    cmhteixeira almost 2 years
    This is incorrect. The difference concerns ownership. A mutex can only be unlocked by the thread that currently holds the lock. That is not true for a semaphore. Check this other related SO question