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

前端 未结 11 1521
梦毁少年i
梦毁少年i 2020-11-27 09:28

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

相关标签:
11条回答
  • 2020-11-27 09:39

    Mutex is binary semaphore. It must be initialized with 1, so that the First Come First Serve principle is met. This brings us to the other special property of each mutex: the one who did down, must be the one who does up. Ergo we have obtained mutual exclusion over some resource.

    Now you could see that a mutex is a special case of general semaphore.

    0 讨论(0)
  • 2020-11-27 09:44

    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)
    0 讨论(0)
  • 2020-11-27 09:44

    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.

    0 讨论(0)
  • 2020-11-27 09:45

    This question has relevant answers and link to official Java guidance: Is there a Mutex in Java?

    0 讨论(0)
  • 2020-11-27 09:50

    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.

    0 讨论(0)
  • 2020-11-27 09:51

    A semaphore is a counting synchronization mechanism, a mutex isn't.

    0 讨论(0)
提交回复
热议问题