In my program I have a function of the following template:
public MyObject myMethod() {
final MyObject[] myObject = new MyObject[]{null};
MyListener myListener= new MyListener() {
public void messageReceived(MyObject newData) {
// Thread #1
myObject[0] = newData;
}
}
...
// Thread #2
while (myObject[0] == null) ;
return myObject[0];
}
Unfortunately, there is a problem with synchronization cause in Java 64-bit Thread #2 doesn’t see any change made by Thread #1 and the while loop never ends. How should I synchronize these threads?
Thanks!
You’re doing a busy loop. This is almost never a good idea. Use a blocking data structure instead, like a BlockingQueue. Once you have received your message, put it in the queue. And have your receiver get the message from the queue. The receiver will be blocked while there is no message in the queue.