Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Synchronized Vs Semaphore

While reading concurrency in Java, I have following doubts:

  1. Does Java provides lower level construct then synchronized for synchronization?

  2. In what circumstances will we use semaphore over synchronized (which provides monitor behaviour in Java)

like image 603
Addict Avatar asked Jun 04 '13 00:06

Addict


People also ask

Is semaphore synchronized?

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.

What is the difference between synchronized and volatile?

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.

How do semaphores synchronize threads?

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.

What is the difference between synchronized and lock?

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.


1 Answers

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.

like image 187
Marichyasana Avatar answered Sep 22 '22 05:09

Marichyasana