[Webinar] Streamline your web hosting managementRegister Today

x
?
Solved

wait() method

Posted on 2000-02-07
24
Medium Priority
?
286 Views
Last Modified: 2013-11-23
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


0
Comment
Question by:plaskowj
  • 11
  • 6
  • 5
  • +2
24 Comments
 

Expert Comment

by:embert
ID: 2496551
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
 
LVL 1

Expert Comment

by:rainmal
ID: 2496567
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
 
LVL 1

Expert Comment

by:rainmal
ID: 2496591
public synchronized void run(){   ???
0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
LVL 5

Expert Comment

by:mbormann
ID: 2496602
>>>>>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
 
LVL 1

Expert Comment

by:rainmal
ID: 2496620
public synchronized void run(){   ???
0
 
LVL 5

Expert Comment

by:mbormann
ID: 2496708
>>>within a synchronized block

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

Expert Comment

by:heyhey_
ID: 2499075
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
 
LVL 5

Expert Comment

by:mbormann
ID: 2499290
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
 
LVL 5

Expert Comment

by:mbormann
ID: 2499327
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
 
LVL 5

Accepted Solution

by:
mbormann earned 800 total points
ID: 2499652
i forgot
private BusyFlag lock;// Data Lock

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

Author Comment

by:plaskowj
ID: 2499668
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
 
LVL 5

Expert Comment

by:mbormann
ID: 2499682
>>>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
 
LVL 1

Expert Comment

by:rainmal
ID: 2499688
Yeah yeah here here here !!!

.....Just kidding.

;-)

0
 

Author Comment

by:plaskowj
ID: 2499703
yes i wolved my problem - but thanks nevertheless
0
 

Author Comment

by:plaskowj
ID: 2499715
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
 
LVL 5

Expert Comment

by:mbormann
ID: 2499723
how ?i am interested
0
 

Author Comment

by:plaskowj
ID: 2499747
So can't answer this one then?
0
 
LVL 1

Expert Comment

by:rainmal
ID: 2499771
plaskowj

It's not such a good idea to stop a thread mid execution
0
 

Author Comment

by:plaskowj
ID: 2499781
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
 
LVL 5

Expert Comment

by:mbormann
ID: 2499782
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
 
LVL 5

Expert Comment

by:mbormann
ID: 2499786
>>>So can't answer this one then?

trying to ...
0
 
LVL 5

Expert Comment

by:mbormann
ID: 2499808
>>>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
 

Author Comment

by:plaskowj
ID: 2499836
can you post me example code- because evertime i open the Asynchron.java file my system crashes

0
 
LVL 5

Expert Comment

by:mbormann
ID: 2499868
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

Featured Post

The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
Suggested Courses
Course of the Month10 days, 21 hours left to enroll

612 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question