Java multithreading-thread communication, java multithreading thread

Source: Internet
Author: User

Java multithreading-thread communication, java multithreading thread

The goal of thread communication is to enable threads to send signals to each other. On the other hand, thread communication enables threads to wait for signals from other threads.

Communication through shared objects

One simple way to send signals between threads is to set the signal value in the variables of the shared object. Thread A sets the boolean member variable hasDataToProcess to true in A synchronization block, and thread B also reads the hasDataToProcess member variable in the synchronization block. This simple example uses a signal holding object and provides the set and check Methods:

public class MySignal{  protected boolean hasDataToProcess = false;  public synchronized boolean hasDataToProcess(){    return this.hasDataToProcess;  }  public synchronized void setHasDataToProcess(boolean hasData){    this.hasDataToProcess = hasData;  }}

Threads A and B must be referenced to A MySignal shared instance for communication. If the references they hold point to different MySingal instances, they cannot detect the signal of each other. The data to be processed can be stored in a shared cache, which is separate from the MySignal instance.

Busy waiting (Busy Wait)

Thread B preparing to process data is waiting for data to become available. In other words, it is waiting for A signal from thread A, which causes hasDataToProcess () to return true. Thread B runs in a loop to wait for this signal:

protected MySignal sharedSignal = ......while(!sharedSignal.hasDataToProcess()){  //do nothing... busy waiting}
Wait (), Policy (), and policyall ()

Busy waiting does not effectively use the CPU that runs the waiting thread unless the average waiting time is very short. Otherwise, it is more wise to let the waiting thread enter sleep or non-running state until it receives the signal it waits.

Java has a built-in wait mechanism to allow threads to become non-running when waiting for signals. The java. lang. Object class defines three methods: wait (), Policy (), and policyall () to implement this wait mechanism.

Once a thread calls the wait () method of any object, it becomes non-running until another thread calls the notify () method of the same object. To call wait () or notify (), the thread must first obtain the Lock of that object. That is to say, the thread must call wait () or notify () in the synchronization block (). The following is the modified version of MySingal-mywaitpolicy using wait () and Policy:

public class MonitorObject{}public class MyWaitNotify{  MonitorObject myMonitorObject = new MonitorObject();  public void doWait(){    synchronized(myMonitorObject){      try{        myMonitorObject.wait();      } catch(InterruptedException e){...}    }  }  public void doNotify(){    synchronized(myMonitorObject){      myMonitorObject.notify();    }  }}

Wait for the thread to call doWait (), while the wake-up thread will call donoworkflow (). When a thread calls the notify () method of an object, it is waiting for all threads of the object to wake up and allow execution (note: the thread to be awakened is random and it cannot be specified which thread to wake up ). At the same time, a yyall () method is provided to wake up all threads waiting for a given object.

As you can see, both the waiting thread and the wake-up thread call wait () and Y () in the synchronization block (). This is mandatory! If a thread does not hold an object lock, it cannot call wait (), Y (), or notifyAll (). Otherwise, an IllegalMonitorStateException is thrown.

(Note: JVM is implemented in this way. When you call wait, it first checks whether the current thread is the lock owner. If not, it throws illegalmonitorstate0000t.)

But how is this possible? When the thread is waiting for execution in the synchronization block, isn't it always holding the lock of the monitor object (myMonitor object? Wait for the thread to block the wake-up thread to enter the synchronization block of the donovel? The answer is: no. Once the thread calls the wait () method, it releases the lock on its monitor object. This allows other threads to call wait () or notify ().

Once a thread is awakened, it cannot immediately exit the wait () method call until it calls notify ()

public class MyWaitNotify2{  MonitorObject myMonitorObject = new MonitorObject();  boolean wasSignalled = false;  public void doWait(){    synchronized(myMonitorObject){      if(!wasSignalled){        try{          myMonitorObject.wait();         } catch(InterruptedException e){...}      }      //clear signal and continue running.      wasSignalled = false;    }  }  public void doNotify(){    synchronized(myMonitorObject){      wasSignalled = true;      myMonitorObject.notify();    }  }}

 

The thread exits its own synchronization block. In other words, the wake-up thread must obtain the lock of the monitor object again to exit the wait () method call, because the wait method call runs in the synchronization block. If multiple threads are awakened by yyall (), only one thread can exit the wait () method at the same time, because each thread is exiting wait () the lock of the monitor object must be obtained before.

Missed Signals)

The notify () and notifyAll () methods do not save the methods that call them, because when these two methods are called, there may be no threads waiting. The notification signal is discarded. Therefore, if a thread calls y () before the notified thread calls wait (), the waiting thread will miss this signal. This may or may not be a problem. However, in some cases, this may cause the waiting thread to wait forever and not to wake up, because the thread missed the wake-up signal.

To avoid signal loss, they must be stored in the signal class. In the mywaitpolicy example, the notification signal should be stored in a member variable of the mywaitpolicy instance. The modified version of mywaitpolicy is as follows:

public class MyWaitNotify2{  MonitorObject myMonitorObject = new MonitorObject();  boolean wasSignalled = false;  public void doWait(){    synchronized(myMonitorObject){      if(!wasSignalled){        try{          myMonitorObject.wait();         } catch(InterruptedException e){...}      }      //clear signal and continue running.      wasSignalled = false;    }  }  public void doNotify(){    synchronized(myMonitorObject){      wasSignalled = true;      myMonitorObject.notify();    }  }}

Note that the doNotify () method sets the wasSignalled variable to true before calling notify. Also, check the wasSignalled variable before calling wait. In fact, if no signal is received between the previous doWait () call and the current doWait () call, it will only call wait ().

(School Note: To avoid signal loss, a variable is used to save whether the notification has been made. You have already been notified of the settings before notify. After wait, you must wait for the notification .)

False Wakeup

For some inexplicable reason, the thread may wake up without calling y () and notifyAll. This is the so-called spurious wakeups ). Woke up without end.

If a false wake-up occurs in the doWait () method of mywait1_y2, wait for the thread to perform subsequent operations even if it does not receive the correct signal. This may cause serious problems in your application.

To prevent false wakeup, the member variables that save the signal will be checked in a while loop, rather than in the if expression. Such a while loop is called a spin lock (note: this practice should be cautious. The current JVM implementation spin will consume the CPU. If the doNotify method is not called for a long time, the doWait method will always spin, CPU usage is too large ). The wake-up thread will spin until the condition in the spin lock (while LOOP) Changes to false. The modified version of mywaitpolicy2 below demonstrates this:

public class MyWaitNotify3{  MonitorObject myMonitorObject = new MonitorObject();  boolean wasSignalled = false;  public void doWait(){    synchronized(myMonitorObject){      while(!wasSignalled){        try{          myMonitorObject.wait();         } catch(InterruptedException e){...}      }      //clear signal and continue running.      wasSignalled = false;    }  }  public void doNotify(){    synchronized(myMonitorObject){      wasSignalled = true;      myMonitorObject.notify();    }  }}

Note that the wait () method is in the while LOOP, not in the if expression. If the waiting thread wakes up without receiving the signal, the wasSignalled variable is changed to false, and the while loop is executed again, prompting the waking thread to return to the waiting state.

Multiple Threads wait for the same signal

If you have multiple threads waiting and are awakened by yyall (), but only one thread is allowed to continue execution, using the while loop is also a good method. Only one thread can obtain the monitor object lock at a time, which means that only one thread can exit the wait () call and clear the wasSignalled flag (set to false ). Once this thread exits the doWait () Synchronization block, other threads exit the wait () call and check the wasSignalled variable value in the while loop. However, this sign has been cleared by the first wake-up thread, so the remaining wake-up threads will return to the waiting state until the next signal arrives.

Do not call wait () in string constants or global objects ()

(Note: The Character String constant mentioned in this chapter refers to a variable whose value is a constant)

In an earlier version of this article, the mywaitpolicy example uses the String constant ("") as the pipe object. The following is an example:

public class MyWaitNotify{  String myMonitorObject = "";  boolean wasSignalled = false;  public void doWait(){    synchronized(myMonitorObject){      while(!wasSignalled){        try{          myMonitorObject.wait();         } catch(InterruptedException e){...}      }      //clear signal and continue running.      wasSignalled = false;    }  }  public void doNotify(){    synchronized(myMonitorObject){      wasSignalled = true;      myMonitorObject.notify();    }  }}

The problem caused by calling wait () and Policy () in the synchronization block (or other constant strings) where an empty string is used as the lock is, the JVM/compiler converts a constant string to the same object. This means that even if you have two different mywaitpolicy instances, they all reference the same Null String instance. It also means that there is a risk that the thread that calls doWait () on the first MyWaitNotify instance will be awakened by the thread that calls donoit () on the second MyWaitNotify instance. In this case, you can draw the following figure:

This may not be a big problem at first. After all, if donovel () is called on the second mywaitpolicy instance, what actually happens is that threads A and B are awakened by errors. The wake-up thread (A or B) will check the signal value in the while loop and return to the waiting state because donovel () is not called on the first mywaitpolicy instance, this is the instance it is waiting. This situation is equivalent to triggering a false wakeup. Thread A or thread B wakes up when the signal value is not updated. But the code handles this situation, so the thread returns to the waiting state. Remember, even if the four threads call wait (), notify (), doWait (), and doNotify () on the same shared string instance () the signal is also saved by two mywaitpolicy instances. A donovel () call on mywait1_y1 may wake up the thread of mywait1_y2, but the signal value will only be saved in mywait1_y1.

The problem is that since donovel () only calls notify () instead of notifyAll (), even if four threads wait on the same string (Null String) instance, only one thread can be awakened. Therefore, if thread A or B is awakened by A signal sent to C or D, it checks its own signal value to see if any signal is received and returns to the waiting status. C and D are not awakened to check the signal values they actually receive, so that the signal is lost. This is equivalent to the previously mentioned problem of signal loss. C and D are sent, but they cannot respond to the signal.

If the doNotify () method calls yyall () instead of notify (), all waiting threads will be awakened and the signal values will be checked in turn. Threads A and B will return to the waiting state, but C or D only has one thread to notice the signal and exit the doWait () method call. The other one in C or D will return to the waiting state, because the thread that obtains the signal clears the signal value (set to false) When exiting doWait ).

After reading the above section, you may try to use policyall () instead of policy (), but this is a bad performance idea. When only one thread can respond to the signal, there is no reason to wake up all threads each time.

Therefore, do not use global objects or string constants in the wait ()/notify () mechanism. Use a unique object. For example, each instance of mywaitpolicy3 has a monitor object of its own, rather than calling wait ()/notify () on an empty string ().

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.