I've read about Semaphore
class there and now what I'd like to understand is how can I use that class in a real code? What is the usefulness of the Semaphores? I got the thing that we could use semaphores in order to improve performance, reducing a concurrency for a resource. Is it the main usage of the Semaphore
?

- 26,175
- 41
- 130
- 318
-
possible duplicate of [What is a semaphore?](http://stackoverflow.com/questions/34519/what-is-a-semaphore) I mean, it includes some examples about "where" to use it. – Furkan Omay Mar 02 '15 at 09:05
-
Semaphores are resources to synchronize processes, Unless you create two processes or more, you should forget semaphores. – CCebrian Mar 02 '15 at 09:05
-
When you need to use concurrency in your application but you want to handle by yourself when a resource is accessible and how many simultaneous accesses to the resource you want to have, you should start thinking on semaphores. – lateralus Mar 02 '15 at 09:07
-
[example](http://www.javacodegeeks.com/2012/10/locking-with-semaphore-example.html) where you can find usage of semaphore – TechnoCrat Mar 02 '15 at 09:13
2 Answers
tl;dr Answer: Semaphores let you limit access to some code path to a certain number of threads - without controlling the mechanism handling those threads. A sample use case is a webservice that offers some resource-intensive task - using a Semaphore, you can limit that task to i.e. 5 threads while using the app server's larger thread pool handle both this and some other types of requests.
Long answer: See Furkan Omay's comment.

- 1,148
- 8
- 17
Semaphores are a part of the concurrency package in java. So as the package says, it is used to leverage the flow of concurrent access to the code. Unlike 'Synchronized' and 'Lock' in java using semaphores you can control the access of your code to a certain number of users.
Consider it as a bouncer in the pub who allows people whether they can enter or not. If the pub is full and cant take any more people he stops until someone leaves. Semaphores can be used to do something like this to your code!!
Hope it helps!!

- 4,522
- 3
- 28
- 37