- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Semaphore in Java
A semaphore is used to control access to a shared resource when a process is being executed. This is done with the help of a counter. When this counter value is greater than 0, access to share resource is provided. On the other hand, if the value of counter is zero, then access to shared resources is denied. The counter basically keeps a count of the number of permissions it has given to the shared resource. This means, a semaphore provides access to a shared resource for a thread.
- Semaphores are present in the java.util.concurrent package. The concept of semaphore is implemented implicitly.
- If the count of semaphore is greater than 0, the thread gets access to shared resource. The count of the semaphore will be decrement simultaneously. Otherwise, if the count of semaphore is not0, the thread would be blocked from accessing the shared resource until the semaphore releases the other thread’s access. When the thread doesn’t need the shared resource, it gives away its permission. At this point in time, the semaphore’s count would be increment. If a different thread also requires access to shared resource, it can compete to access the shared resource.
Example
Following is an example −
public class Demo { private boolean my_signal = false; public synchronized void accept() { this.my_signal = true; this.notify(); } public synchronized void give_it() throws InterruptedException { while(!this.my_signal) wait(); this.my_signal = false; } }
The ‘accept’ method is used to send a signal that is stored inside a semaphore. The ‘give_it’ function waits for a signal. When this function receives a signal, its flag is cleared, and the control exits from this function. Using a semaphore in this manner, none of the signals would be missed.
- Related Articles
- Semaphore in C#
- Mutex vs Semaphore
- Difference Between Semaphore and Mutex
- Difference Between Semaphore and Monitor in OS
- Semaphore and Mutex in FreeRTOS using Arduino
- Race Condition, Critical Section and Semaphore
- How semaphore is used to implement mutual exclusion?
- How can a binary semaphore implement mutual exclusion among n processes?
- Java Stream Collectors toCollection() in Java
- Java program to calculate mode in Java
- Convert Java String to Short in Java
- Compare Two Java int Arrays in Java
- Greedy quantifiers Java Regular expressions in java.
- Is Java matcher thread safe in Java?
- How to Sort a String in Java alphabetically in Java?
