Junior — Middle
What types of monitoring objects are used in Java and how do they function?
sobes.tech AI
Answer from AI
In Java, a monitor is a synchronization mechanism built into each object that allows managing access to shared resources in a multithreaded environment.
Types of monitor objects in Java:
-
Object's intrinsic monitor — each object in Java has an associated monitor. The
synchronizedkeyword is used to acquire and release this monitor. -
ReentrantLock from the
java.util.concurrent.lockspackage — a more flexible locking mechanism that also implements the monitor concept but with additional features (e.g., attempting to acquire the lock with a timeout).
How they work:
- When a thread enters a
synchronizedblock, it acquires the object's monitor. - Other threads trying to enter the same block or method will be blocked until the monitor is released.
- This ensures mutual exclusion (mutex), preventing concurrent access to critical sections.
Example of using the intrinsic monitor:
public class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public synchronized int getCount() {
return count;
}
}
Here, the increment and getCount methods are synchronized, ensuring correctness when accessed from multiple threads.