user16647
user16647

Reputation: 165

Trouble with a thread-safe queue class. Specifically, with exceptions

I am using a thread-safe queue class and have a problem with the insert method I've defined. A Buffer stores an array (elementData) that uses the start/end variables to know where to add/delete stuff from the queue. It's thread-safe, so it uses synchronized methods so I can have multiple threads refer to the same buffer.

public class Buffer<T> {
    private T[] elementData;                     
    private int elementCount;
    private int start;                                      
    private int end;

    // Additional fields

    // Code to instantiate a Buffer, other methods (e.g. delete)

    public synchronized void insert(T t) throws InterruptedException {
        while (elementCount == elementData.length) {
            wait();
        }
        end = (end + 1) % elementData.length;
        elementData[end] = t;
        elementCount++;
        notifyAll();
    }

    public static void main(String[] args) {
        Buffer<Integer> b = new Buffer();
        b.insert(3);
    }
}

Here's my understanding of the situation. When a method such as insert is called, we want to be able to throw an exception that could happen when the main method or some other thread gets called and tries to perform insert while it's suspended. But what I don't understand is why I get this unreported exception. I thought that having a "throws InterruptedException" after the method would be sufficient. Do I need a "try" block? My attempts with try blocks have all failed, so I'm a little stumped as to how to fix this error.

Also, I'm aware that I don't have any actual threads running. I'll do those once I can fix this unreported exception. :) Thanks to anyone who can help.

Buffer.java:56: unreported exception java.lang.InterruptedException; must be caught or declared to be thrown
b.insert(3);

Upvotes: 0

Views: 117

Answers (1)

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85789

The compile exception is because your insert method could throw an InterruptedException (even if you're not throwing it on purpose), so every method that calls it must use a try/catch block, even if the error never arises:

public static void main(String[] args) {
    Buffer<Integer> b = new Buffer();
    try {
        b.insert(3);
    } catch(InterruptedException ie) {
        //error handling
        e.printStackTrace();
    }
}

Upvotes: 2

Related Questions