Java Threading Mechanism (v) waiting and notification mechanism

Source: Internet
Author: User
Tags requires sleep thread valid

In our previous discussion of stopping thread, we used the practice of setting tags, once the done set is true, the thread will end, and once false, the thread will run forever. This will consume a lot of CPU cycles and is an unfriendly behavior to memory.

Objects in Java not only have locks, but they themselves can make themselves wait and notify by invoking related methods.

Object objects themselves have two methods: Wait () and notify (). Wait () waits for the condition to occur, and notify () notifies the waiting thread that this condition has already occurred and that they must be invoked from the synchronized method or block.

What is the purpose of such a waiting-notification mechanism?

The wait-notification mechanism is a synchronization mechanism, but it is more like a communication mechanism that allows one thread to communicate with another thread under a particular condition. However, the mechanism does not specify what specific conditions are.

Can waiting-notification mechanism replace synchronized mechanism? Of course not, wait-notification mechanism does not solve the competition problem that the synchronized mechanism can solve, in fact, the two are in cooperation with each other, and it also has competition problem, which needs to be solved by synchronzied.

Private Boolean done = true;
    
Public synchronized void Run () {while
      (true) {
            try{
                 if (do) {wait
                       ();
                 } else{
                       repaint ();
                       Wait (m);
                 }
            catch (Interruptedexception e) {return
                  ;
            }
    
}} Public synchronized void Setdone (Boolean b) {done
     = B;
     if (timer = = null) {
          timer = new Thread (this);
          Timer.start ();
     }
     if (!done) {
          notify ();
     }
}

The done here is not volatile, because we do not just set a tag value, we also need to set the tag at the same time automatically send a notification. So, we are now using synchronized to protect the done access.

The run () method does not automatically exit when done to false, and it makes the thread wait in this method by calling the waiting () method until the other thread calls the Notify () method.

Here are a few places we should pay attention to.

First, we hibernate the thread by using the Wait () method instead of the sleep () method. Because the wait () method requires the thread to hold a synchronous lock on the object, the lock is released when the Wait () method is executed, and the thread is required to wait while the notification is received () method to regain the lock before returning it, as if holding a lock all the time. This technique is because there is competition between setting up and sending notifications and testing and getting notifications, if Wait () and notify () are not invoked while holding a synchronous lock, there is no way to guarantee that the notification will be received, and if the waiting () method does not release the lock before it waits, It is not possible for the Notify () method to be invoked because it cannot get the lock, which is another reason why we use wait () instead of sleep (). If you use the sleep () method, the lock will never be freed, and the Setdone () method will never be executed, and the notification will never be sent.

And then here we are synchronizing the run (). As we discussed before, it is very dangerous to synchronize run () because the run () method is absolutely impossible to accomplish, that is, the lock will never be released, but because the wait () itself releases the lock, the problem is avoided.

We have a question: if the Notify () method is invoked, there is no thread waiting?

The wait-notification mechanism does not know the condition of the notification being sent, and it assumes that the notification is not received when no thread is waiting, because it simply returns and the notification is lost, and the thread that later executes the wait () method must await another notification.

As we have said, the waiting-notification mechanism itself has a competitive problem, which is a irony: the mechanism used to solve the problem of synchronization itself is also a problem! In fact, competition is not necessarily a problem, as long as it does not cause problems on the line. Now let's analyze the competition here:

A thread that uses wait () confirms that the condition does not exist, usually by examining the variable, before we call the () method. The Notify () method is invoked when other threads set up the condition, usually by setting the same variable. Competition occurs in the following situations:

1. The first thread tests the condition and confirms that it needs to wait;

2. The second thread sets this condition;

3. The second thread calls the Notify () method, which is not received because the first thread has not yet entered the wait;

4. The first thread invokes the Wait () method.

This competition requires synchronous locks to be implemented. We must obtain the lock to make sure that the condition is checked and set to Automic, that is, the inspection and setting must be in the lock range.

As we mentioned above, the Wait () method releases the lock and then retrieves the lock, so is there any competition happening during this period? Theoretically there will be, but the system will prevent this. The wait () method is tightly bound to the lock mechanism, and the lock of an object is not actually released until the waiting thread has entered a state that is ready to receive notification.

Our question continues: Does the thread receive notification that the condition is set correctly? Sorry, the answer is no. Before the Wait () method is invoked, the thread should always test the condition when it holds the synchronization lock, and when returned from the Wait () method, the thread should never again test the condition to determine if it still needs to be waited, because other threads can also test the condition and determine that there is no need to wait. It then processes the valid data that is set by the thread that issued the notification. But this is in the case of only one thread waiting for the notification, if multiple threads are waiting for the notification, there will be competition, and this is the wait-notification mechanism can not be resolved, because it resolves only the internal competition to prevent the loss of notice. The biggest problem with multithreading waiting is that when a thread receives notification after another thread is notified, it cannot guarantee that the notification is valid, so the waiting thread must provide the option to check the status and return to the waiting state when the notification has been processed, which is why we always have to wait () The reason for putting it inside the loop.

Wait () will also be returned ahead of time when its thread is interrupted, and our program must also handle the interrupt.

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.