Re: Simple(?) synchronized() block question



Hi,
So basically u r getting this error coz u r calling wait method
implicitly on 'this' and synchronizing String s. so if u write s.wait()
it solves ur problem.

I hope it helps...


noident@xxxxxxxxxxx wrote:
Greetings!
I am trying to make a simple thread/conncurrency example work.
What I am trying to do in the following simple code example is:
1. Start a thread
2. Make the started thread become another object's (String s) monitor
by executing a synchronized() statement
3. Call wait().
But it fails with an IllegalMonitorStateException.
If I understand the documentation correctly, I am under impression that
if the code within the synchronized() {} block is executing, the thread
is already the monitor of the object it's synchronizing on, but that
seems not to be the case :(
The following simple program fails, and I can't figure out what's
wrong. I must be missing something simple.

import java.util.*;

public class Foo extends Thread
{
private String s;
public Foo(String ss) { s = ss; }

public void run()
{
synchronized(s) // changing this line to 'synchronized(this)' fixes
the problem
{
try
{
wait();
}
catch(InterruptedException e)
{
System.err.println(e);
System.exit(1);
}
}
}

public static void main(String[] args)
{
new Foo("abc").start();
}
}

Running the above produces this:
Exception in thread "Thread-0" java.lang.IllegalMonitorStateException
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:474)
at Foo.run(Foo.java:14)

my java version is:
java version "1.5.0_06"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_06-b05)
Java HotSpot(TM) Client VM (build 1.5.0_06-b05, mixed mode)

Any suggestions will be very much appreciated.

.



Relevant Pages

  • Simple(?) synchronized() block question
    ... is already the monitor of the object it's synchronizing on, ... The following simple program fails, and I can't figure out what's ... public static void main ... java version "1.5.0_06" ...
    (comp.lang.java.programmer)
  • Re: programming concepts > specific languages
    ... > public static void manipulateString{ ... > What actually happens in Java though is "String A" gets printed out. ... public static void manipulateObject(Object objectToManipulate) ...
    (comp.programming)
  • AW: beginners question
    ... public static void main (String[] args) ... and set the Javadoc ... |> If I saw an experienced java programmer writing this program, ...
    (comp.lang.java)
  • newbee in java programming
    ... public static void main(String[] args) ... On my machine I have this java version ...
    (comp.lang.java.programmer)
  • Re: Really simple: how to call a class from another class
    ... >sorry but it's been a long time since I programmed in java and have ... >called decode.java and I want to send it a string from the main class ... >public static void main{ ... class names, ie. Decode and Read. ...
    (comp.lang.java.programmer)