1

I'm trying to write a code which wants to make a write thread. When I want to run it, I got this exception. Each post that I saw about this topic didn't have the code same as mine. So can any one help me about my problem?

java.lang.IllegalMonitorStateException

The stacktrace is as below:

    at java.lang.Object.wait(Native Method)
    at java.lang.Object.wait(Object.java:485)
    at prj.McWThread.ReadPacket(McWThread.java:40)
    at prj.McWThread.run(McWThread.java:73)

The part of code that makes this exception is :

public void run()
{
    try{
        while (true)
        {
            this.MyPkt = ReadPacket();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(MyPkt);
       }
       }
}

Readpacket method:

public MyPacket ReadPacket()
{
    MyPacket m = new MyPacket();
    System.out.println("ReadPacket");
    try {
        while (Buff.isEmpty()) {
            wait();
        }
    }
    catch (InterruptedException ie) {
        ie.printStackTrace();
    }

    if (! Buff.isEmpty()) {
        m = (MyPacket) Buff.remove(0);
        return m;
    } else {
        return m;
    }
}
Raedwald
  • 46,613
  • 43
  • 151
  • 237
S Kh
  • 105
  • 2
  • 9

2 Answers2

3

You need to synchonize your call to wait in your code. Two Options:

  • Declare your method as syncronised

    public syncronized MyPacket ReadPacket()

  • use synchronized(this) before your call to wait.

The first one may not be advisable depending on your design and the work other threads need to carry out, if any.

For the second option, again, you need to be sure if you would want to use this as your monitor. You can create a Lock and use that instead.

Ravi Bhatt
  • 3,147
  • 19
  • 21
1

The javadoc for Object.wait.

"The current thread must own this object's monitor." and "[throws] IllegalMonitorStateException - if the current thread is not the owner of the object's monitor." You need to synchronize on the object you are going to call the wait on.

The code should look something like

synchronize(someobject){
   someobject.wait();
}
Sajan Chandran
  • 11,287
  • 3
  • 29
  • 38
  • You should always [wait in a loop](http://stackoverflow.com/questions/1038007/why-should-wait-always-be-called-inside-a-loop). – assylias Nov 26 '12 at 11:54
  • I'm using wait in a loop, too. (As I post my ReadPacket method above) – S Kh Nov 26 '12 at 11:59