Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Semaphore and synchronization

I could not quite understand the following from the semaphore description in javadocs.

Note that no synchronization lock is held when acquire() is called as that would prevent an item from being returned to the pool. The semaphore encapsulates the synchronization needed to restrict access to the pool, separately from any synchronization needed to maintain the consistency of the pool itself.

Can someone please help me understand this and its implications.

like image 910
Ajex Avatar asked Oct 15 '10 02:10

Ajex


People also ask

What is semaphore in synchronization?

Semaphore is simply an integer variable that is shared between threads. This variable is used to solve the critical section problem and to achieve process synchronization in the multiprocessing environment. Semaphores are of two types: Binary Semaphore – This is also known as mutex lock.

Is semaphore used for synchronization?

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.

Why is semaphore known as synchronization?

So, when the value of the semaphore variable goes to 0 i.e all the resources are taken by the process and there is no resource left to be used, then if some other process wants to use resources then that process has to wait for its turn. In this way, we achieve the process synchronization.

What is a semaphore used for?

semaphore, method of visual signaling, usually by means of flags or lights. Before the invention of the telegraph, semaphore signaling from high towers was used to transmit messages between distant points.


1 Answers

A semaphore acts as a limiter of available resource pool depth; for example, a semaphore with a capacity of 10 allows a maximum of 10 threads to acquire it at once, and any further threads that attempt to acquire it will block until one of the other threads releases it.

This is somewhat different from ordinary mutual exclusion or monitor locking, which is typically used to prevent more than one thread from simultaneously modifying the same variables and causing inconsistent results or program state.

Consider, for example, a connection pool with a limit of 10 connections in it. Each thread that needs a connection will acquire the semaphore for the duration of its use of a connection (which prevents too many threads asking for connections at once), but the pool object must also use synchronized blocks or methods when taking connections out of its internal collection or putting them back in, to prevent such things as losing track of connections or mistakenly handing the same connection to two different threads because they asked simultaneously.

like image 157
Jeffrey Hantin Avatar answered Oct 21 '22 15:10

Jeffrey Hantin