Java Semaphore example
GIAN Tutorials
8:41 AM
Semaphore is a class in java.util.concurrent package introduced in JDK 5. Semaphore basically maintains a set of permits, so there are two methods which are mainly used for semaphore. acquire release acquire() method is used to get a permit and if no. of permits reaches max allowed permits then thread has to wait to get permit which will be released by some other thread by calling release() method. Semaphores are generally used to restrict the number of threads to access resources. Real time examples: Semaphores can be used to restrict number of database connections at a time Semaphores can also be used to bound any collection. Example: We will create a class BoundedArrayList which can have only 5 elements at a time. If any thread wants to add more element to the list, thread will have to wait until any other thread remove elements from the list. When we add an element to the list, we will call semaphore.acquire and when we remove an element from the list, we