Synchronized keyword and monitor lock in java
- Manbodh ratre
- Sep 11, 2024
- 1 min read
Synchronization is used to handle concurrency issue in java,
concurrency means handling multiple things at same time, let's suppose 2 thread want to use same resource at a same time so handling this situation is know as concurrency , concurrency can be achieved by synchronized keyword or locking on a resource.
let's understand this using below example, here synchronized block acquire the monitor lock on SharedResource class
here I have create one sharedResource class and one variable isAvailable = false initially,
in the main method first i am calling produce and consume method using 2 different threads , but before here i wanted to call first consume method that's why i have used Thread.sleep(10) to call consumer first and then consumer will wait for a producer to produce the isAvailable = true
when the consumer thread acquired the monitor lock then produces thread can not acquired the monitor lock again mean it cannot run produce() method, because it is already acquired by consumer, when consumer execute the wait() method it release the monitor lock and then producer thread can acquire the lock again. and can do the task
Main class to test the above code example
Output:
consumer acquired a monitor lock Thread-1
consumer released monitor lock Thread-1
producer acquired a monitor lock Thread-0
please let me know if you have any doubt or suggestion in the comment
happy coding!!
Comments