Reputation: 5177
Is the Synchronized keyword in java depend on a Mutex or a Semaphore ? I read that both these terms are used interchangeably, but there is a difference ? Are there any built in Semaphore classes in java ?
Upvotes: 1
Views: 1684
Reputation: 612
Semaphore has a fixed number of permits which can be acquired/released while running a block of code. So a fixed number of threads equal to number of permits can run a code block at the same time. Mutex/Lock is a specialized version of the Semaphore where the number of permits is 1. That is only a single thread is allowed to run a certain code block. This gives the thread 'ownership' of the code block. Only the owner can acquire and release the lock on the code block.
Upvotes: 0
Reputation: 14853
synchronized are implemented in term of Thread Monitor
java.util.concurrent.locks is a package which contains some useful lock relative classes like ReentrantLock
Upvotes: 0
Reputation: 6095
The main difference between a mutex
and a semaphore
is that the mutex
may be released only by the process/thread that holds it in contrast to the semaphore
that may be released by any process/thread. There is also one more difference but not as significant: there is a kind of semaphore that is called counting semaphore, i.e. a semaphore that may be initialized to allow several concurrent 'holders'.
The synchronized
access in Java semantically should be implemented using mutex
.
Upvotes: 1