Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do Java semaphores use busy waiting or a wait/notify by default?

As the question goes. I'm using the JDK 6.0 on Windows 7, and am attempting to use semaphores as a mechanism to solve a synchronization problem. It works perfectly, but I'm trying to avoid busy waiting in my problem.

I would just ask the java documentation and spare SO the trouble, but the docs go like this:

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

Acquires the given number of permits, if they are available,
 and returns immediately, reducing the number of available permits
 by the given amount.

If insufficient permits are available then the current thread
 becomes disabled for thread scheduling purposes and lies dormant

http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/Semaphore.html#acquire(int)

That is to say, the docs seem to be implying both answers. Which one is correct?

like image 449
Faqa Avatar asked Nov 14 '22 12:11

Faqa


1 Answers

I don't see how it's implying busy-waiting at all. It clearly states that the thread is "disabled" and dormant. Basically, it's cheap: the thread won't consume processor time while it's waiting to acquire the semaphore.

like image 97
Jon Skeet Avatar answered Nov 16 '22 02:11

Jon Skeet