-1

I have a MyService class which contains a nested BroadcastReceiver class:

public class MyService {
   private Object lock;
   public class MyReceiver extends BroadcastReceiver {
      @Override
      public void onReceive(Context context, Intent intent) {
         synchronized(lock) {
           doTask();
           lock.wait();
           Log.d(TAG, "After wait ...");
         }
      }
   } 
   private synchronized void doTask() {
      Log.d(TAG, "do task ...");
      synchronized(lock) {
          lock.notify();
      }
   }
}

As you see above, when onReceive() is called, my code run doTask() in a synchronized block. Then, in doTask() function, my code run lock.notify(). I expected to see the log in terminal Log.d(TAG, "After wait ...");

I run my Android project. When onReceive() is triggered, I can see the log "do task ...", then, it is hanging there, I can't see log "After wait ...", why my wait-notify is not working as expected?

user842225
  • 5,445
  • 15
  • 69
  • 119
  • The same thread is calling both methods? – Sotirios Delimanolis Dec 06 '15 at 16:40
  • Possibly a "lost notification". http://stackoverflow.com/questions/5999100/is-there-a-block-until-condition-becomes-true-function-in-java/26218153#26218153 `lock.notify()` _does not do anything at all_ unless some other thread is already waiting in a `lock.wait()` call. – Solomon Slow Dec 06 '15 at 19:41

1 Answers1

0

I run my Android project. When onReceive() is triggered, I can see the log "do task ...", then, it is hanging there, I can't see log "After wait ...", why my wait-notify is not working as expected?

BroadcastReceivers run always on the ui thread. if MyService runs on the Ui thread, what you are experiencing is a deadlock. It could be also that MyService runs on a background thread. If the notify is executed before wait, then the thread running MyService is waiting for the next notify

Blackbelt
  • 156,034
  • 29
  • 297
  • 305