Given Below Is A Generic Class Circular Queue That Implements A Queue Modeled By A Circular Array: Parallel And Distributed Programming Assignment, GCD, Ireland

Question 1

Given below is a generic class Circular Queue that implements a queue modeled by a circular array. There are two constructors a default one that sets the size to an arbitrary value of 20 and one that takes the maximum size of the queue as an argument n.

In both cases, the head and tail are set to zero. This class is not thread-safe. Please note that a queue simply manages the order of insertion and removal, it does not interact in any way with the data under its control. Your task is to re-write it so that it is thread-safe and solves issues that may arise around iteration.

class CircularQueue<T> implements Iterable<T>{
private T queue[];
private int head, tail, size;
public CircularQueue(){
queue = (T[])new Object[20];
head = 0; tail = 0; size = 0;
}
public CircularQueue(int n){ //assume n >=0
queue = (T[])new Object[n];
size = 0; head = 0; tail = 0;
}
public boolean join(T x){
if(size < queue.length){
queue[tail] = x;
tail = (tail+1)%queue.length;
size++;
return true;
}
else return false;
}
public T top(){
if(size > 0)
return queue[head];
else
return null;
}
public boolean leave(){
if(size == 0) return false;
else{
head = (head+1)%queue.length;
size–;
return true;
}
}
public boolean full(){return (size == queue.length);}
public boolean empty(){return (size == 0);}
public Iterator<T> iterator(){
return new QIterator<T>(queue, head, size);
}
private static class QIterator<T> implements Iterator<T>{
private T[] d; private int index;
private int size; private int returned = 0;
QIterator(T[] dd, int head, int s){
d = dd; index = head; size = s;
}
public boolean hasNext(){ return returned < size;}
public T next(){
if(returned == size) throw new NoSuchElementException();
T item = (T)d[index];
index = (index+1) % d.length;
returned++;
return item;
}
public void remove(){}
}
}

No Comment.