HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Java blocking queue

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
queueblockingjava

Problem

public class BQueue {

    private Queue q = new LinkedList();
    private int limit;

    public BQueue(int limit) {
        this.limit = limit;
    }

    public synchronized void put (T t) throws InterruptedException {
        while (isFull()) {
            wait();
        }
        boolean e = isEmpty();
        q.add(t);
        if (e)
            notifyAll();
    }

    public synchronized T get () throws InterruptedException {
        while (isEmpty()) {
            wait();
        }
        boolean f = isFull();
        T t = q.poll();
        if (f)
            notifyAll();
        return t;
    }

    private boolean isEmpty() {
        return q.size() == 0;
    }
    private boolean isFull() {
        return q.size() == limit;
    }
}


Is this implementation thread-safe?

Solution

Yes, it's thread-safe. (Or at least I haven't found any issue.) Please note, that the Java Collections Framework already has a BlockingQueue interface which has some implementations, for example a LinkedBlockingQueue (source). It's probably well tested add has better performance, so try not to reinvent the wheel if it's not necessary.

Some other notes:

-
Try using longer variable names:

boolean f = isFull();


It could be isFull which results more readable code. The same is true for q and t. (I'd rename it to queue and item.)

-
Check your input: What happens when limit is 0 or less than zero? (You should throw an IllegalArgumentException.)

-
The limit and q fields could be marked final. It would improve code readability since readers don't have to check whether their values have changed somewhere in the class or not. It also would prevent accidental value modifications.

-
The used Queue has an isEmpty method (by implementing Collection.isEmpty()), you could use that instead of your own.

Code Snippets

boolean f = isFull();

Context

StackExchange Code Review Q#7002, answer score: 8

Revisions (0)

No revisions yet.