Java semaphore and monitors

Explain semaphore and monitors in java threading.

A semaphore is a flag variable used to check whether a resource is currently being used by another thread or process.
The drawback of semaphores is that there is no control or guarantee of proper usage.

A Monitor defines a lock and condition variables for managing concurrent access to shared data. The monitor uses the lock to ensure that only a single thread is active in the monitor code at any time.

A semaphore is a generalization of a monitor. A monitor allows only one thread to lock an object at once.

Explain the concepts of semaphore and monitors in Java threading.

Semaphore:
A semaphore is a construct in multithreading. It is a construct that can be used to send signals between synchronized threads in order to avoid missing signals. It can also be used to guard critical operations such as dead locks.

Monitor:
Thread monitor supports the threads which are synchronized and mutual exclusion and co-operation. Multiple threads will work independently on shared data without interfering each other with the help of object locks concept. Cooperation between threads is performed with the usage of wait() and notify() methods of Object class. Cooperation is enabling threads work together for a common goal.

Synchronization allows the threads to execute one after another without interrupting the thread that is running. Monitor contains special memory location which allows storing a thread’s data and handles one at a time.
What are Checked and UnChecked Exception?
Java checked and unchecked exception - The java.lang.Throwable class has two subclasses Error and Exception. There are two types of exceptions...
Java inner classes: What are different types of inner classes?
Java inner classes - Types of inner classes - Local classes, Member classes, Anonymous classes...
Java wrapper classes
What is wrapper classes in Java?, Why do we need wrapper classes in Java?, Features of the Java wrapper Classes...
Post your comment