unknown
unknown

Reputation: 13

Implementing a synchronized queue in Java using ArrayList

I've been working on a project where I need a synchronized queue, for the reason that my program is multi-threaded and the thread may access this queue. I used arraylist to do that, but I seem to have some issues with it and threads got deadlocked. I don't know if the queue is the reason, but I just wanted to check:

public class URLQueue {
    private ArrayList<URL> urls;

    public URLQueue() {
        urls = new ArrayList<URL>();
    }

    public synchronized URL remove() throws InterruptedException {
        while (urls.isEmpty())
            wait();
        URL r = urls.remove(0);
        notifyAll();
        return r;
    }

    public synchronized void add(URL newURL) throws InterruptedException {
        urls.add(newURL);
        notifyAll();
    }

    public int getSize() {
        return urls.size();
    }
}

EDITS: Even when using LinkedBlockingQueue I get stuck in the same loop as before. I think this is caused because there is a thread which is waiting for the queue to be filled, but it never does because the other functionalities are done running...any ideas???

Upvotes: 1

Views: 4366

Answers (2)

vishal_aim
vishal_aim

Reputation: 7854

It is better to use LinkedBlockingQueue here as it is designed for that purpose. It waits until some element is available while trying to remove an alement.

LinkedBlockingQueue

It provides a take() method which

Retrieves and removes the head of this queue, waiting if necessary until an element becomes available

Upvotes: 4

Peter Lawrey
Peter Lawrey

Reputation: 533442

In your code, notifyAll() doesn't throw InterruptedException so you should remove the throws from add()

The remove() method doesn't need to notifyAll() as it's action shouldn't wake other threads.

The getSize() method should be synchronized.

Otherwise there is no chance for your code to deadlock as you need two locks to create a deadlock.

Upvotes: 0

Related Questions