Question

When I am using the wait() method in the following code its throwing the following Exeption

Exception in thread "AWT-EventQueue-0" java.lang.IllegalMonitorStateException

The code is as follows:

private void newMenuItemActionPerformed(java.awt.event.ActionEvent evt) {                                            
        newFileChooser = new JFileChooser();

        int returnVal = newFileChooser.showSaveDialog(null);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            filename = newFileChooser.getSelectedFile();
            JFrame mainFrame = NetSimApp.getApplication().getMainFrame();
            networktype = new NetType(mainFrame);
            networktype.setLocationRelativeTo(mainFrame);
            NetSimApp.getApplication().show(networktype);
            try {
                this.wait();
            } catch (InterruptedException ex) {
               Logger.getLogger(NetSimView.class.getName()).log(Level.SEVERE, null, ex);
            }
            if (!NetType.validip) {
                statusTextArea.append("File not created:Select Network Type.\n");
            }
            newNodeMenuItem.setEnabled(true);
        } else {
             newNodeMenuItem.setEnabled(false);
            statusTextArea.append("File not created:Access cancelled by user.\n");
        }
    }

Actually I am calling the object of a jDialog class and i want that the dialog object should complete first and then it should notify the above given code. I've already specified notify() in that class. Can anyone tell me whats the problem and its solution. -Thanks in advance

Was it helpful?

Solution

Your wait method needs to be enclosed in a synchronized method or a lock block, with the object being locked on the object you want to wait upon.

In your case, you should make the method synchronized, which is equivalent to calling lock (this).

OTHER TIPS

You have to start wait by acquiring synchronization on the wait variable, e.g.

synchronized( this )
{
    this.wait( );
}

Please read the javadoc for wait carefully and follow it to the letter, otherwise you'll be up to nasty surprises.

  1. synchronized block of code where "wait()" is
  2. don't "notify" Thread, "notify" runnable, Thread is a Control class for runnable and Thread wraps notify/notifyAll/wait with monitor class
  3. try using interupt and throw a "non-error" throwable to pause/resume thread.
  4. use producent/consumer approach
  5. use fork/join approach
  6. use Thread pool for pausing and resuming thread (pause - kill runnable, resume - pool runnable)

Any of these approaches would eliminate your problem, the problem itself is that you try to notify already notified thread, its same problem like starting already started thread. It will throw a IllegalMonitorStateException.

Thread is a horribly written solution to Process but its not so hard to manage.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top