While reading concurrency in Java, I have following doubts:
Does Java provides lower level construct then synchronized for synchronization?
In what circumstances will we use semaphore over synchronized (which provides monitor behaviour in Java)
A semaphore is an integer variable, shared among multiple processes. The main aim of using a semaphore is process synchronization and access control for a common resource in a concurrent environment.
Synchronized is applicable only on blocks or methods. Volatile is applicable to variables only. The synchronized modifier is used to implement a lock-based concurrent algorithm, i.e it suffers from the limitation of locking.
A thread waits for permission to proceed and then signals that the thread has proceeded by performing a P operation on the semaphore. The thread must wait until the semaphore's value is positive, then change the semaphore's value by subtracting 1 from the value.
Major difference between lock and synchronized: with locks, you can release and acquire the locks in any order. with synchronized, you can release the locks only in the order it was acquired.
Synchronized allows only one thread of execution to access the resource at the same time. Semaphore allows up to n (you get to choose n) threads of execution to access the resource at the same time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With