Results 1 to 4 of 4
Thread: InterruptedException and Locks
- 02-02-2010, 12:41 AM #1
Member
- Join Date
- Jan 2010
- Posts
- 26
- Rep Power
- 0
InterruptedException and Locks
Java Code:synchronized (signallingObject) { while (!signalled) { try { signallingObject.wait(); } catch (InterruptedException ex) { /*@Todo LOGME */ System.err.println("Value Updater Interrupted"); /* Check to see if i have been told to quit */ if (!isRunning) { /* Signal before exit */ signalled = false; signallingObject.notify(); break mainloop; } } } }
the try catch block is within the signallingobject synch scope. When wait is called we give up the lock. What happens to the lock if we are interrupted, are we blocked until we can regain the lock (Assuming another thread has the objects lock when the exception is caught). Or have we found ourselves in strange state where two threads are inside one objects synch block.
- 02-04-2010, 11:10 AM #2
Member
- Join Date
- Jan 2010
- Posts
- 26
- Rep Power
- 0
My own tests seem to indicate the lock is recovered after the catch.
- 02-12-2010, 07:35 AM #3
Senior Member
- Join Date
- Jan 2009
- Posts
- 671
- Rep Power
- 13
The wait can not exit without reaquiring the lock, even to handle an exception. Rest assured that it is impossible for two threads synchronized on the same object to run simultaneously under any condition.
- 02-19-2010, 02:47 AM #4
I'm not sure what you are doing, but you can't notify() unless you already own the monitor. Since you released the monitor with wait(), you must not be executing the notify(). Further, I doubt that the monitor is reacquired within the loop.
First, move your synchronized block as close to the wait() as you can. In this case, it should at least be within the while block, if not the try.
Second, you must reacquire the monitor by adding a second synchronized around the notify(), since wait() released it.
Third, all that activity inside a catch block looks suspicious. It may end up doing what you want, but if you can't look at your code and know immediately what it is doing, you probably need to come up with a cleaner solution.
Similar Threads
-
whether this will throw 'InterruptedException' or 'IllegalStateException'
By vysh in forum New To JavaReplies: 2Last Post: 05-28-2009, 05:09 PM -
Thread Safe Methods / Locks
By mrhyman in forum Threads and SynchronizationReplies: 16Last Post: 10-24-2008, 09:57 PM -
Error: java.lang.InterruptedException is not caught and does not appear...
By fernando in forum Advanced JavaReplies: 1Last Post: 07-31-2007, 05:52 AM
Bookmarks