0

I have a java implementation of a monitor using

java.util.concurrent.locks.Lock;
java.util.concurrent.locks.ReentrantLock;
java.util.concurrent.locks.Condition;

The problem that I'm solving is a readers/writers problem. I have one lock lock & two conditions readers and writers.

I've noticed that the Condition.await() function throws InterruptedException. For now, I've just surrounded the method with a try / catch block. However, the catch block is empty.

I'm wondering when this exception is thrown and how I should be dealing with it.

readers.await() is called when there is a writer writing to a file / there are writers waiting to write to a file.

writers.await() is called when there are one or more readers reading from a file OR a writer is currently writing to a file.

In what cases will InterruptedException be thrown, and how should I deal with them?

connorbode
  • 3,015
  • 1
  • 28
  • 31

1 Answers1

0

Interrupting allows to stop some long/blocking tasks in context of a thread. InterruptedException happens only when someone has set "is interrupted" flag for the given thread.

Now regarding await(). When your thread A is waiting on Condition.await(),usually this means it is parked by

LockSupport.park(Object blocker); (-> sun.misc.Unsafe.park(boolean bln, long l) for Hotspot). Something like this:

    public void await() throws InterruptedException {
        if (Thread.interrupted()) {
            throw new InterruptedException();
        }

        while (still_waiting) {
            LockSupport.park(this);
            if (Thread.interrupted()) {
                throw new InterruptedException();
            }
        }
    }

Now let's assume the user stops the application. The main thread calls A.interrupt() to finish your thread A. interrupt() is implemented in native Thread.interrupt0(). This call set "is interrupted" flag of the thread and unparks the thread A and the thread sees that it is interrupted and throws InterruptedException.

It depends on system requirements how to catch the InterruptedException. If your thread does some work in the loop, you should break the loop to let the thread to be finished. Also, it is good practice to set "is interrupted" flag back for the current thread if you've just catch an InterruptedException:

    try {
         ...
         some.await();
     }
     catch (InterruptedException e) { 
         // Restore the interrupted status
         Thread.currentThread().interrupt();
     }

An old but still good article: http://www.ibm.com/developerworks/java/library/j-jtp05236/index.html?ca=drs-

AnatolyG
  • 1,557
  • 8
  • 14