49

I try to notify adapters of listviews of main class in onPostExecute but I receive the error: java.lang.IllegalMonitorStateException:object not locked by thread before notify()

@Override
protected void onPostExecute(String result) {
    popularfragment.adapter.notifyDataSetChanged();
    recentfragment.adapter.notifyDataSetChanged();
} 
Erkan Erol
  • 1,334
  • 2
  • 15
  • 32

2 Answers2

97

The .notify() method has to be called from within a synchronized context, ie from inside a synchronized block.

The java.lang.IllegalMonitorStateException is thrown when you call .notify() on an object that is not used as the lock for the synchronized block in which you call notify. For example, the following works;

synchronized(obj){
    obj.notify();
}

But this will throw the exception;

synchronized(obj){
    // notify() is being called here when the thread and 
    // synchronized block does not own the lock on the object.
    anotherObj.notify();        
}

Reference;

Community
  • 1
  • 1
Rudi Kershaw
  • 12,332
  • 7
  • 52
  • 77
3

I had the same error, but (for me) the answer suggested by Rudi Kershaw wasn't the issue... I called the notify() of a Notification the wrong way (see the last line of both snippets):

Not working:

public void update() {
    mBuilder.setSmallIcon(R.drawable.ic_launcher)
            .setPriority(AesPrefs.getInt(R.string.PRIORITY_NOTIFICATION_BATTERY, NotificationCompat.PRIORITY_MAX))
            .setOngoing(true);
    mBuilder.setWhen(AesPrefs.getLong(Loader.gStr(R.string.LAST_FIRED_BATTERY_NOTIFICATION) + Const.START_CLIPBOARD_NOTIFICATION_DELAYED, -1));
    mManager.notify(); // <- lil' mistake
}

Working:

public void update() {
    mBuilder.setSmallIcon(R.drawable.ic_launcher)
            .setPriority(AesPrefs.getInt(R.string.PRIORITY_NOTIFICATION_BATTERY, NotificationCompat.PRIORITY_MAX))
            .setOngoing(true);
    mBuilder.setWhen(AesPrefs.getLong(Loader.gStr(R.string.LAST_FIRED_BATTERY_NOTIFICATION) + Const.START_CLIPBOARD_NOTIFICATION_DELAYED, -1));
    mManager.notify(Const.NOTIFICATION_CLIPBOARD, mBuilder.build()); // <- ok ;-)
}
Martin Pfeffer
  • 12,471
  • 9
  • 59
  • 68
  • hey i used your code but i don't know where Const has been declared plz tell me – Mahdi Javaheri Feb 10 '16 at 12:17
  • Const contains constant values in my project. Press Ctrl+P (set the cursor on "notifiy" and press the shortcut) to see the parameter info -> its an Integer (something like an ID you have to give the notification). You can also add a new Class called "Const", simply press Alt+Enter when the cursor is on Const and select create "new class". ;) Got it? *NOTE:* if you have multiple notifications, they need to have different IDs. To clear the notification you will use this ID as well. – Martin Pfeffer Feb 10 '16 at 12:38