I came up with the following for a blocking and non-blocking queue implementation. Please suggest any changes/improvements/gotchas.
Blocking queue:
public class BlockingQueue<T> {
List<T> buffer;
private static final int MAX_QUEUE_SIZE = 100;
public BlockingQueue() {
buffer = new ArrayList<T>();
}
public void enqueue(T value) throws InterruptedException {
synchronized(buffer) {
while(buffer.size() >= MAX_QUEUE_SIZE) {
buffer.wait();
}
buffer.add(value);
buffer.notifyAll();
}
}
public T dequeue() throws InterruptedException {
synchronized(buffer) {
while(buffer.size() < 1) {
buffer.wait();
}
T value = buffer.remove(0);
buffer.notifyAll();
return value;
}
}
}
Non-blocking queue:
public class NonBlockingQueue<T> {
List<T> buffer;
private static final int MAX_QUEUE_SIZE = 100;
private AtomicBoolean mutex = new AtomicBoolean(false);
public NonBlockingQueue() {
buffer = new ArrayList<T>();
}
public void enqueue(T value) throws InterruptedException {
while(true) {
while(!mutex.compareAndSet(false, true)) {
Thread.sleep(100);
}
if(buffer.size() < MAX_QUEUE_SIZE) {
buffer.add(value);
mutex.set(false);
return;
} else {
mutex.set(false);
}
}
}
public T dequeue() throws InterruptedException {
T value = null;
while(true) {
while(!mutex.compareAndSet(false, true)) {
Thread.sleep(100);
}
if(buffer.size() > 0) {
value = buffer.remove(0);
mutex.set(false);
return value;
} else {
mutex.set(false);
}
}
}
}
I think by non-blocking it means that the thread should not be blocked, so I used the sleep
method. Please let me know if it has any issues.
THread.sleep(100)
is a terrible idea, and it also blocks. So "no." C.f.: ibm.com/developerworks/library/j-jtp04186 – markspace Oct 3 at 5:32