Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the acquire() method in Semaphores not have to be synchronized?

I am getting into Semaphores in Java and was reading this article http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/Semaphore.html . The only thing I don't get is why the acquire() method is not used in a synchronized context. Looking at the example from the above webiste:

They create a semaphore:

private Semaphore semaphore = new Semaphore(100);

and get a permit just like this:

semaphore.acquire();

Now, wouldn't it be possible that two or more threads try to acquire() at the same time? If so, there would be a little problem with the count.

Or, does the semaphore itself handle the synchronization?

like image 508
user1420042 Avatar asked Feb 15 '13 10:02

user1420042


People also ask

How do semaphores synchronize threads?

Semaphore is a synchronization technique where we can control number of threads to access a resource. In lock/Mutex, only one thread can access resources at a time. But Semaphore allows multiple threads to access the same resource at a time. We can limit the number of threads that can access the same resources.

When called the method Acquire () of the Java semaphore class will?

Method SummaryAcquires a permit from this semaphore, blocking until one is available, or the thread is interrupted. Acquires the given number of permits from this semaphore, blocking until all are available, or the thread is interrupted.

Can multiple threads acquire binary semaphore?

Multiple number of threads can acquire binary semaphore at a time concurrently.

Can release be called on a semaphore before acquire?

Yes, a negative value means you have processes waiting for the semaphore to be released. A positive value means you can call acquire that many times before the semaphore blocks.


2 Answers

Or, does the semaphore itself handle the synchronization?

Yes that's basically it. Semaphores are thread safe as explained in the javadoc:

Memory consistency effects: Actions in a thread prior to calling a "release" method such as release() happen-before actions following a successful "acquire" method such as acquire() in another thread.

Most operations on the objects in the java.util.concurrent package are thread safe. More details are provided at the very bottom of the package javadoc.

like image 71
assylias Avatar answered Sep 20 '22 23:09

assylias


Semaphores ought to be fast and therefore use the atomic concurrency primitives from the Unsafe class, like CAS (compare and swap).

With these primitives synchronization happens on a much lower level and monitors are not needed. (Lock-free synchronization).

In fact the synchronization is performed by a loop continously using CAS until the expected value equals the written/read value.

like image 28
Neet Avatar answered Sep 24 '22 23:09

Neet