How do I avoid busy loop in Java Thread with callback function
callback, java, multithreading
Solution
Do something like this
class MyThread implements Runnable, MessageListener{
private Listen Listener;
private Object lock = new Object();
public MyThread(){
Listener = new Listener(this);
}
public void run(){
while(true){
synchronized (lock) {
try{
lock.wait();
// use the updated status
}catch (Exception e) {
e.printStackTrace()
}
}
}
}
public void messageReceived(Message m){
synchronized (lock) {
try{
// Do something with the message here like update some status
lock.notify();
}catch (Exception e) {
e.printStackTrace()
}
}
}
Once you get the event, you update some status/ store the message and release the notifying Thread. Then from your thread process the event
Problem
I am trying to figure out how to eliminate a busy loop in a thread I have in Java. The thread does nothing but wait for a callback from the Listener class. The thread class looks something like this: ``` class MyThread implements Runnable, MessageListener{ private Listen Listener; public MyThread(){ Listener = new Listener(this); } public void run(){ while(true){} } public void messageReceived(Message m){ //do stuff } } ``` I have tried to make this code as simple as possible. The idea is that Listener is waiting to receive some data from a serial port and when a message is received the thread will do some processing on it. I would prefer to use some synchronized variables such as a BlockingQueue of Message but I can't modify the Listener code. The issue, of course, is that the run loop eats up processor cycles. My questions: If I wait or sleep in the run loop will the function call still work as expected? (I'm not sure how to test that this works 100% of the time). Is there some better way to avoid this loop altogether?