1

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!

peter
  • 631
  • 2
  • 7
  • 18
  • what is the main prupose of using this? – Alex Stybaev May 18 '12 at 10:44
  • Seems to be common excercise (homework) nowadays... did you check that? http://stackoverflow.com/questions/10649166/in-java-7-64-bit-my-program-freezes-on-a-loop – home May 18 '12 at 10:44
  • @AlexStybaev This is a part of something bigger. I simplified it for this question purpose. – peter May 18 '12 at 10:46
  • Do you know about the keyword volatile? I don't know how to use it here. It seems that in order to simplify the code for SO, you have made your problem trivial, but I guess its a similar situation. Read about volatile here http://www.javamex.com/tutorials/synchronization_volatile.shtml – Ozair Kafray May 18 '12 at 10:47
  • @home But here I've got a local variable so I cannot use volatile. – peter May 18 '12 at 10:47

3 Answers3

1

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.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • 1
    I think "never a good idea" is a tad too strong. There are plenty of contexts in low-latency programming where busy loops are a jolly good idea. – NPE May 18 '12 at 11:06
1

Try to use the java.util.concurrent.ArrayBlockingQueue instead of Array... then you wont have to use synchronized keyword. Its thread safe .

Kumar Vivek Mitra
  • 33,294
  • 6
  • 48
  • 75
1

You may use Synchronized block on myObject object (as it is never null) in both the threads.

synchronized(myObject) {
    ...do stuff ...
}

A suggestion: instead of using while loop, use wait-notify mechanism.

Vasu
  • 4,862
  • 8
  • 42
  • 48