1

Here I am using wait() method in try block for the inter communication between threads. I used wait method outside the try block but it was showing exception.

try
{
    System.out.println(" why we should use wait() method in try block  ");
    wait();
}
    catch()
    {
    }
}
HDJEMAI
  • 9,436
  • 46
  • 67
  • 93
Nisha Singh
  • 11
  • 1
  • 3
  • 4
    If you look at the [JavaDocs for `Object#wait`](https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#wait--), you will see it throws two exceptions, `IllegalMonitorStateException`, which is a `RuntimeException` and `InterruptedException` which is a caught exception, which you MUST handle, so, no, you must call `wait` in a `try-catch` OR re throw the exception – MadProgrammer Jun 25 '17 at 03:14
  • As @MadProgrammer says, you must either catch the InterruptedException, or your method needs to declare that it throws it – okaram Jun 25 '17 at 03:22

1 Answers1

3

Q: Why should we use wait() method inside the try block?

You use a wait() inside a synchronized block or synchronized method.

synchronized (this) {
    while (!this.isTeapot) {
        this.wait();
    }
    System.out.println("I am a teapot");
}

And in another method ...

synchronized (this) {
    this.isTeapot = true;
    this.notify();
}        

Why?

  • Because the spec says so.
  • Because you will get an IllegalMonitorStateException if you don't.

But why?

  • Because it is not possible to implement wait / notify condition variables safely without this restriction. The requirement is essential for thread safety; i.e. to avoid race conditions and memory anomalies.

The try block is not mandatory. Use a try block if you need to deal with an exception at that level. If not, allow it to propagate. This includes InterruptedException ... though since it is a checked exception, you would need to declare it in the method's throws clause if you didn't catch it locally. But this is just normal Java exception handling. Nothing special.

For example:

try {
    synchronized (this) {
        while (!this.isTeapot) {
            this.wait();
        }
        System.out.println("I am a teapot");
    }
} catch (InterruptedException ex) {
    Thread.currentThread().interrupt();
}

(For an explanation of the above example, see Why would you catch InterruptedException to call Thread.currentThread.interrupt()?.)

Q: Can we use wait() method outside the try block?

You cannot call wait() outside of a synchronized block or synchronized method. (See above.)

The try block is not mandatory. (See above.)

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • up!!!hi, you may need write a simple example. e.g: a synchronized method throws exceptions that `wait` will be threw. – holi-java Jun 25 '17 at 03:27