Why Wait () and notify () must use sychronized

Source: Internet
Author: User
Why Wait () and notify () must use sychronized

If not, will error illegalmonitorstateexception. first, it is clear that the implementation basis for Wait () and notify () is based on the existence of objects. So why is it based on object existence?

Here to be clear, waiting is a signal sent by an object, so to exist based on the object.

Since it is object-based, it has to use a data structure to hold these waiting threads, and the data structure should be bound to that object, at which point there may be multiple threads calling the Wait ()/notify () method.

When writing and deleting data in a doubly linked list to this object, there is still a concurrency problem, which in theory requires a lock to control. In the JVM kernel source code does not discover any oneself to use the lock to control writes the action, only by checking whether the current thread is the object owner to determine whether to throw the corresponding exception. This shows that it wants the action to be controlled by the abstraction level of the Java program, why it does not want to control the lock itself.

Because sometimes a lower level of abstraction is not necessarily a good thing, because such requests may be recycled over and over again, or the code might be reused elsewhere, perhaps it would be better to be coarse-grained, and such code would be clearer in the Java program itself. It is easier to see the relationship between each other.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.