Object not locked by thread before notify() in onPostExecute

Ask Question

Asked5 years, 4 months ago

Active3 years, 9 months ago

Viewed56k time

41

2

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();
} 

java
android
multithreading

share
improve this question

asked
Jun 12 ’14 at 13:38

Erkan Erol

65411 gold badge77 silver badges2323 bronze badges

add a comment

2 Answers

active
oldest
votes

81

The.notify()method has to be called from within asynchronizedcontext, ie from inside asynchronizedblock.

Thejava.lang.IllegalMonitorStateExceptionis 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;

IllegalMonitorStateException API

How to use wait & notify

share
improve this answer

editedMay 23 ’17 at 11:55

Community

111 silver badge

answered
Jun 12 ’14 at 13:48

Rudi Kershaw

7,72555 gold badges3838 silver badges6969 bronze badges

add a comment

2

I had the same error, but (for me) the answer suggested by Rudi Kershaw wasn’t the issue… I called thenotify()of a Notification the wrong way (see thelast lineof 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 ;-)
}

share
improve this answer

answered
Dec 29 ’15 at 20:19

Martin Pfeffer

8,59877 gold badges4444 silver badges6060 bronze badges

add a comment

https://stackoverflow.com/questions/24185921/object-not-locked-by-thread-before-notify-in-onpostexecute

Similar Posts: