• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

IllegalMonitorStateException

 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

I have two classes running on different threads and both use the same resource.

"isUpdateNeeded" is the var that I want to update (the lock). The method "setUpdateVar()" change the value of this variable to true and notify the thread "UpdateVar" to use this variable. The issue occurs when notifyAll() is called:

java.lang.IllegalMonitorStateException: object not locked by thread before notifyAll()


Could anyone help me to understand how to lock/unlock properly in this example?



Many thanks in advance




public static void setUpdateVar() {
synchronized (isUpdateNeeded){
while(isUpdateNeeded == true){
try {
isUpdateNeeded.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
isUpdateNeeded = true;
isUpdateNeeded.notifyAll();
}
}


private class UpdateVar extends Thread {
boolean isRunning = true;

public void run() {
while(isRunning) {
synchronized (isUpdateNeeded){
if (isUpdateNeeded == true){

isUpdateNeeded = false;

mHandler.post(new Runnable() {
public void run() {
ShowList();
}
});
}
}
}
}
}


 
Bartender
Posts: 4179
22
IntelliJ IDE Python Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I assume isUpdateNeeded is a Boolean (or a boolean that autoboxes to a Boolean). If this is the case, then changing the value from true to false (or vice-versa) actually changes the Object referred to by isUpdateNeeded. IE When true, is is Boolean.TRUE and when false it is Boolean.FALSE, two separate Objects, which means you can't synchronize/notify between them.

To simplify things you should have a separate lock that can't change:


 
Ana Martin
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks a lot. It works great with your solution!
Thanks for the explanation
 
Don't count your weasels before they've popped. And now for a mulberry bush related tiny ad:
Clean our rivers and oceans from home
https://www.kickstarter.com/projects/paulwheaton/willow-feeders
reply
    Bookmark Topic Watch Topic
  • New Topic