Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception on calling wait() method of Object class [closed]

Tags:

java

oop

The below code doesn't execute even after notifying the current thread (using this).

public synchronized void test() {
    String str = new String();
    try {
        System.out.println("Test1");
        this.wait();
        this.notifyAll();
        System.out.println("Test2");
    } catch (Exception e) {
        // TODO Auto-generated catch block
        System.out.println("Inside exception");
        e.printStackTrace();
    }
 }

I get only Test1 as output on the console.

In, the second case I get the exception if I call the wait method on string object. The reason is because the string class object str doesn't hold lock on current object. But I wonder what does str.wait() actually means ?

public synchronized void test() {
    String str = "ABC";
    try {
        System.out.println("Test1");
        str.wait();
        str.notifyAll();
        System.out.println("Test2");
    } catch (Exception e) {
        // TODO Auto-generated catch block
        System.out.println("Ins");
        e.printStackTrace();
    }
 }

Console Output:

> Test1  
java.lang.IllegalMonitorStateException
like image 203
user1921476 Avatar asked Dec 03 '25 11:12

user1921476


1 Answers

Not sure what you expected from that code:

  1. In your first example, wait does what it says: it waits, so notifyAll is never called
  2. In the second example, you can't call wait on an object without holding the monitor of that object first. So you would need to be in a synchronized(str) block to avoid the exception. But you would still have the same issue as in 1.

The main use case of wait and notify is inter-thread communication, i.e. one thread waits and another thread notifies that waiting threads can wake up. In your case the same thread is at both ends of the communication channel which does not work.

like image 176
assylias Avatar answered Dec 06 '25 00:12

assylias



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!