wait() method

I have a thread with a run method:


public void run(){
     for(;;){
        do something.....
        try{
            wait()
        }catch(InterruptedException e){

        }
}
the problem i am having is that on runtime i get an IllegalMonitorStateException - current thread not owner


can anyone tell me how to fix this


plaskowjAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

embertCommented:
wait() must be called within a synchronized method. otherwise the IllegalMonitorStateException will be thrown.

try the following:

                   public synchronized void run(){
                        for(;;){
                           do something.....
                           try{
                               wait()
                           }catch(InterruptedException e){

                           }
                   }


then it should work fine.
0
rainmalCommented:
That cause the wait() method must be called from a synchronized method or block.

you can call wait on the object you want to synchronize
within a synchronized block

For Example

Class Example
{
   StingBuffer buf = new String buffer
   
   void SomeMethod
   {
     // Do Something
     synchronized (buf)
     {
         try
         {
             buf.wait()
         }catch (Exception e){}
     }
   }
}

You could then call this method from run

0
rainmalCommented:
public synchronized void run(){   ???
0
Cloud Class® Course: Amazon Web Services - Basic

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

mbormannCommented:
>>>>>public synchronized void run()

Well ,if u keep it as synchronized then no other thread will go inside run() so how do you keep it as a Thread?

The whole purpose of threading is then defeated.
0
rainmalCommented:
public synchronized void run(){   ???
0
mbormannCommented:
>>>within a synchronized block

public void run()
{
//some code
try
{
    synchronized(this)
   {
        wait();
   }
}
catch(Exception e)
{}
//some code
}
0
heyhey_Commented:
1.
public synchronized void run()
{  
// code
}

is absolutely the same as

public void run()
{  
synchronized (this)
{
// code
}
}

2. when you are inside the wait(), the lock is 'unlocked' so other Thread may access this object.
0
mbormannCommented:
heyhey,
my comment was

>>>         public void run()
                {
                //some code
                try
                {
                    synchronized(this)
                   {
                        wait();
                   }
                }
                catch(Exception e)
                {}
                //some code
                }

so referring to code above if u have synchronized void run() then as said b4 no threads will be able to access the run() when one thread is inside it,but seeing the code which is b4 and after the wait() in the synchronized block ,it is a better alternative to the above,and it's not the same but yes it's not elegant either.
:)

we are totally ignoring the question and I will post someting afterwards.
0
mbormannCommented:
use this class

/*
 * by Scott Oaks and Henry Wong.
 */

public class BusyFlag
{
    protected Thread busyflag = null;
    protected int busycount = 0;

    public synchronized void getBusyFlag()
    {
        while (tryGetBusyFlag() == false)
        {
            try
            {
                wait();
            }
            catch (Exception e)
            {}
        }
    }

    public synchronized boolean tryGetBusyFlag()
    {
        if (busyflag == null)
        {
            busyflag = Thread.currentThread();
            busycount = 1;
            return true;
        }
        if (busyflag == Thread.currentThread())
        {
            busycount++;
            return true;
        }
        return false;
    }

    public synchronized void freeBusyFlag()
    {
        if (getBusyFlagOwner() == Thread.currentThread())
        {
            busycount--;
            if (busycount == 0)
            {
                busyflag = null;
                notify();
            }
        }
    }

    public synchronized Thread getBusyFlagOwner()
    {
        return busyflag;
    }
}

Use ti like this

    public void run()
    {
        try
        {
            while (true)
            {
      //code
      try
                {
                    lock.getBusyFlag();
      
       //more code
                }
                finally
                {
                    lock.freeBusyFlag();
                }
            }

        }
        catch (Exception e)
        {
            return;
        }
    }

hope it helps
0
mbormannCommented:
i forgot
private BusyFlag lock;// Data Lock

public YourClass()
{
lock = new BusyFlag();// Allocate sync variables
}
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
plaskowjAuthor Commented:
Just returned, and have been inundated with solutions- which wasn't that hard to figure out.

Anyhow as you posted the most - i will award it to you.

But, if any others feel cheeted, i will award them points as well - just ask
0
mbormannCommented:
>>>Anyhow as you posted the most - i will award it to you.

No if it solves ur problem then and only then u shuld award otherwise whats the use?did u solve ur problem?
0
rainmalCommented:
Yeah yeah here here here !!!

.....Just kidding.

;-)

0
plaskowjAuthor Commented:
yes i wolved my problem - but thanks nevertheless
0
plaskowjAuthor Commented:
Anyhow whilst i am about it, and seeing that you feel generous to asnwer my questions - how can i sopt a thread mid execution.


without using interrupt- i.e. whilst the thread is hanging on IO stream
0
mbormannCommented:
how ?i am interested
0
plaskowjAuthor Commented:
So can't answer this one then?
0
rainmalCommented:
plaskowj

It's not such a good idea to stop a thread mid execution
0
plaskowjAuthor Commented:
But lets say i am reading a URL and i want to stop it taking to much time.

how do i stop it - maybe stop is not the right word
0
mbormannCommented:
u can take a look at this site and buy this book ,it is the best and easy to learn too

http://www.oreilly.com/catalog/jthreads2/

Java Threads, 2nd Edition
 By Scott Oaks & Henry Wong
 2nd Edition January 1999

Click on the Examples link at left of site,open AsyncInputStream.java in chapter 5

>>>how can i sopt a thread mid execution without using interrupt- i.e. whilst the thread is hanging on IO stream.

Note that both the read() and write() are blocking calls i.e they 'hang' so ur question is a bit ambiguos rephrase it again.
0
mbormannCommented:
>>>So can't answer this one then?

trying to ...
0
mbormannCommented:
>>>But lets say i am reading a URL and i want to stop it taking to much time.

you implement a timeout and if the thread goes into read() or write() and 'hangs' for the next set of data u HAVE to send a thread.interrupt() and catch in the respective read() the InterruptedException and return -1 to indicate EOF.

u send the thread.interrupt() from another thread and not the one in which u are doing the read() or write(),there u do the checks of timeout.
0
plaskowjAuthor Commented:
can you post me example code- because evertime i open the Asynchron.java file my system crashes

0
mbormannCommented:
import java.net.*;
import java.io.*;

public class AsyncInputStream extends FilterInputStream implements Runnable {
      private Thread runner;            // Async Reader Thread
      private byte result[];            // Buffer
      private int reslen;            // Buffer Length
      private boolean EOF;            // End-of-File Indicator
      private IOException IOError;      // IOExceptions

      BusyFlag lock;                  // Data Lock
      CondVar empty, full;            // Signal Variables

      protected AsyncInputStream(InputStream in, int bufsize) {
            super(in);

            lock = new BusyFlag();            // Allocate sync variables
            empty = new CondVar(lock);
            full = new CondVar(lock);

            result = new byte[bufsize];      // Allocate Storage Area
            reslen = 0;                  // and initialize variables
            EOF = false;
            IOError = null;
            runner = new Thread(this);       // Start Reader Thread
            runner.start();
      }

      protected AsyncInputStream(InputStream in) {
            this(in, 1024);
      }

      public int read() throws IOException {
            try {
                  lock.getBusyFlag();
                  while (reslen == 0) {
                        try {
                              if (EOF) return(-1);
                              if (IOError != null) throw IOError;
                              empty.cvWait();
                        } catch (InterruptedException e) {}
                  }
                  return (int) getChar();
            } finally {
                  lock.freeBusyFlag();
            }
      }

      public int read(byte b[]) throws IOException {
            return read(b, 0, b.length);
      }

      public int read(byte b[], int off, int len) throws IOException {
            try {
                  lock.getBusyFlag();
                  while (reslen == 0) {
                        try {
                              if (EOF) return(-1);
                              if (IOError != null) throw IOError;
                              empty.cvWait();
                        } catch (InterruptedException e) {}
                  }

                  int sizeread = Math.min(reslen, len);
                  byte c[] = getChars(sizeread);
                  System.arraycopy(c, 0, b, off, sizeread);
                  return(sizeread);
            } finally {
                  lock.freeBusyFlag();
            }
      }

      public long skip(long n) throws IOException {
            try {
                  lock.getBusyFlag();
                  int sizeskip = Math.min(reslen, (int) n);
                  if (sizeskip > 0) {
                        byte c[] = getChars(sizeskip);
                  }
                  return((long)sizeskip);
            } finally {
                  lock.freeBusyFlag();
            }
      }

      public int available() throws IOException {
            return reslen;
      }

      public void close() throws IOException {
            try {
                  lock.getBusyFlag();
                  reslen = 0;            // Clear Buffer
                  EOF = true;            // Mark End Of File
                  empty.cvBroadcast();      // Alert all Threads
                  full.cvBroadcast();
            } finally {
                  lock.freeBusyFlag();
            }
      }

      public void mark(int readlimit) {
      }

      public void reset() throws IOException {
      }

      public boolean markSupported() {
            return false;
      }

      public void run() {
            try {
                  while (true) {
                        int c = in.read();
                        try {
                              lock.getBusyFlag();
                              if ((c == -1) || (EOF)) {
                                    EOF = true;            // Mark End Of File
                                    in.close();            // Close Input Source
                                    return;                  // End IO Thread
                              } else {
                                    putChar((byte)c);  // Store the byte read
                              }
                              if (EOF) {
                                    in.close();            // Close Input Source
                                    return;                  // End IO Thread
                              }
                        } finally {
                              lock.freeBusyFlag();
                        }
                  }

            } catch (IOException e) {
                  IOError = e;                    //  Store Exception
                  return;
            } finally {
                  try {
                        lock.getBusyFlag();
                        empty.cvBroadcast();                    //  Alert all Threads
                  } finally {
                        lock.freeBusyFlag();
                  }
            }
      }

      private void putChar(byte c) {
            try {
                  lock.getBusyFlag();
                  while ((reslen == result.length) && (!EOF)) {
                        try {
                              full.cvWait();
                        } catch (InterruptedException ie) {}
                  }
                  if (!EOF) {
                        result[reslen++] = c;
                        empty.cvSignal();
                  }
            } finally {
                  lock.freeBusyFlag();
            }
      }

      private byte getChar() {
            try {
                  lock.getBusyFlag();
                  byte c = result[0];
                  System.arraycopy(result, 1, result, 0, --reslen);
                  full.cvSignal();
                  return c;
            } finally {
                  lock.freeBusyFlag();
            }
      }

      private byte[] getChars(int chars) {
            try {
                  lock.getBusyFlag();
                  byte c[] = new byte[chars];
                  System.arraycopy(result, 0, c, 0, chars);
                  reslen -= chars;
                  System.arraycopy(result, chars, result, 0, reslen);
                  full.cvSignal();
                  return c;
            } finally {
                  lock.freeBusyFlag();
            }
      }
}
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.