This week's book giveaway is in the JavaScript forum.
We're giving away four copies of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js and have Paul Jensen on-line!
See this thread for details.
Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

IllegalMonitorStateException  RSS feed

 
venkatesh pendharkar
Ranch Hand
Posts: 106
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi ,
I was trying following code

class A
{
void met(Object s)
{
synchronized(this)
{
System.out.println(Thread.currentThread()+"["+s);
System.out.println(Thread.holdsLock(this));
try
{
Thread.sleep(1000);
Thread.currentThread().wait();//...line1
}
catch (InterruptedException e)
{
}
System.out.println(s+"]");
}
}
}

class D implements Runnable
{
A ob;
String s;
D(A a,String b)
{
s=b;
ob=a;
Thread t=new Thread(this);
t.start();
}
public void run()
{
ob.met(s);
}
public static void main(String[] args)
{
A a1=new A();
D d1=new D(a1,"java");
D d2=new D(a1,"synchronized");
}
}

In this code there are 2 objects d1 & d2 are created which try to access the synchronized method met() on the same object a1.On line 1 i have called wait() method beacuse of which current thread leaves the monitor & 2nd thread(of obejct d2) starts executing met().
I dont understand why is it giving "IllegalMonitorStateException" when 2nd thread reaches wait() method although "System.out.println(Thread.holdsLock(this));" returns true for both the threads.
Also one thing i observed is if instead of "Thread.currentThread().wait();" if we call only "wait()" then it doesnt throw any exception.

Please help me in this.
 
Vlado Zajac
Ranch Hand
Posts: 245
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You should use "wait();" instead of "Thread.currentThread().wait();" to wait on the A object (a1).

wait() is a method of Object not Thread and it always causes current thread to stop.

The reason for exception is that this!=Thread.currentThread() (inside met method). The code holds lock on this but tries to wait on Thread.currentThread().
 
venkatesh pendharkar
Ranch Hand
Posts: 106
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ok so you mean that wait() should be called on current object & not on current thread...& Thread.currentThread() doent return refference of current object;it returns ref.for current thread. Am i correct?
Anyways thanks a lot for helping me out in this
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!