Results 1 to 3 of 3
  1. #1
    vysh is offline Member
    Join Date
    Apr 2009
    Posts
    11
    Rep Power
    0

    Default whether this will throw 'InterruptedException' or 'IllegalStateException'

    Hi all,

    Given the code,

    Java Code:
    class syncTest
    {
    void waitForSignal() 
    {
    	Object obj = new Object();
    	synchronized (Thread.currentThread()) 
    	{
    		obj.wait();
    		obj.notify();
    	}
    }
    }
    The options given are :

    A. This code may throw an InterruptedException.
    B. This code may throw an IllegalStateException.
    C. This code may throw a TimeoutException after ten minutes.
    D. This code will not compile unless "obj.wait()" is replaced with "((Thread) obj).wait()".
    E. Reversing the order of obj.wait() and obj.notify() may cause this method to complete normally.
    F. A call to notify() or notifyAll() from another thread may cause this method to complete normally.
    The answer is B.

    I compiled the code and got InterruptedException. Since the obj.wait() is not given in the try catch block, the InterruptedException is thrown(I believe). But how come the correct answer is given as B, i.e., IllegalStateException. Can anyone clear my doubt?

  2. #2
    OrangeDog's Avatar
    OrangeDog is offline Senior Member
    Join Date
    Jan 2009
    Location
    Cambridge, UK
    Posts
    838
    Rep Power
    6

    Default

    You should get an IllegalStateException because the current thread is not synchronised on obj when obj.wait() is called.
    Don't forget to mark threads as [SOLVED] and give reps to helpful posts.
    How To Ask Questions The Smart Way

  3. #3
    vysh is offline Member
    Join Date
    Apr 2009
    Posts
    11
    Rep Power
    0

    Default

    orangedog,

    Did you try to compile the program? Because when I compiled the program I got the following error:

    unreported exception java.lang.InterruptedException; must be caught or declared to be thrown
    obj.wait()
    When i enclosed the obj.wait() in try, catch block, i got IllegalMonitorStateException.

    How come i am getting that exception. (As i know, the IllegalMonitorStateException occurs when the current thread is not the owner of the object). How this exception differs from IllegalStateException?

Similar Threads

  1. Replies: 2
    Last Post: 12-14-2009, 02:46 AM
  2. throw exception
    By GIRISH PATEL in forum New To Java
    Replies: 4
    Last Post: 04-23-2009, 05:35 AM
  3. throw an exception
    By sfe23 in forum New To Java
    Replies: 3
    Last Post: 02-14-2009, 05:41 AM
  4. Difference between Throws and Throw
    By Poonam in forum New To Java
    Replies: 7
    Last Post: 02-06-2008, 05:52 PM
  5. Replies: 1
    Last Post: 07-31-2007, 06:52 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •