Interview Question
Quality Assurance EngineersCountry: India
Are you reading the questions at all ? "Make it thread safe" - where is thread safe in your code.
public class Queue {
private String[] array = null;
private int start = 0;
private int end = -1;
static private int currSize = 0;
static private boolean isDataAdded = false;
private int queueSize = 0;
public Queue(int size){
this.array = new String[size];
this.queueSize = size;
}
public synchronized void enQueue(String data) throws InterruptedException{
if(currSize >= this.queueSize){
System.out.println("queue is full to enQueue "+Thread.currentThread().getName()
+" is blocked till queue will get deQueue'd");
this.wait();
}else if(currSize <= this.queueSize){
this.end ++;
this.array[this.end] = data;
currSize ++;
isDataAdded = true;
System.out.println(data+" added to queue by "+Thread.currentThread().getName());
this.notify();
}
}
public synchronized String deQueue() throws InterruptedException {
String queueData = null;
if(currSize <= 0){
System.out.println("queue is empty to deQueue "+Thread.currentThread().getName()
+" is blocked till queue will get enQueue'd");
this.wait();
}else if(currSize > 0){
queueData = array[start];
array[start] = null;
if(isDataAdded){
this.end = ((this.start == 0) ? -1 : this.end);
isDataAdded = false;
}
this.start++;
currSize--;
if(this.start >= this.queueSize || currSize == 0){
this.start = 0;
this.end = -1;
}
this.notify();
System.out.println(queueData+" removed from queue by "+Thread.currentThread().getName());
}
return queueData;
}
}
- avico81 January 27, 2013