These methods works on the locks and locks are associated with Object and not Threads. Hence, it is in Object class.
The methods wait(), notify() and notifyAll() are not only just methods, these are synchronization utility and used in communication mechanism among threads in Java.
Synchronization: The concept of synchronization will make sure that only one Thread is accessing an object/resource at the same time.
Java concurrency model uses locks to implement mutually exclusive access to objects in a multi-threaded environment. Locks are associated with objects not with the Threads. Hence, Locks are made available on per Object basis.
In Java, to achieve mutually exclusive access on objects, a threads needs to acquire lock and other threads needs to wait to acquire lock. And they don’t know which threads holds lock instead they just know the lock is hold by some other thread and they should wait for lock instead of knowing which thread is inside the synchronized block and asking them to release lock. This analogy fits with wait and notify being on object class rather than thread in Java.
Example:
I would like to discuss with a well known example to get a clear understanding of this topic. Let’s take a real time banking scenario. Suppose two or more customers having a joint account, which can be permitted to perform the transactions through multiple channels like Teller, ATM, Mobile Banking, and Internet Banking. Currently the account having the balance 2000/- and the first user trying to purchase worth of 1500/- through Internet Banking other user trying to withdraw 1500/- through ATM. Here whichever the channel first access the account to perform the transaction will acquires a lock and other channel will wait for the lock. The channel which is waiting for lock status is not aware of which channel acquires the lock and at the same time the channel which is already acquired the lock is not aware of that who are waiting to acquire lock on the particular account. Here lock is applied on the account and not on channel.
ref:
No comments:
Post a Comment