I was trying to solve the Single Producer & Consumer problem, As per the problem statement from wikipedia https://en.wikipedia.org/wiki/Producer%E2%80%93consumer_problem Production and Consumption should happen endlessly such that the producer should not add to queue when it is full and consumer should not consume when it is empty
I have solved it using Thread.sleep and a double check using continue in the infinite while loop and created two threads one producer and consumer, It seems to run fine without breaking, but I did not find this solution recommended elsewhere, I have attached the code
My question is will this solution break or does it have any performance hit when compared to locking or using produce/consume count,
Code:
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Random;
class Buffer{
static final int MAX_SIZE=5;
static Deque<Integer> bufferQueue=new ArrayDeque<>();
static int produce(){
int value=new Random().nextInt(10);
bufferQueue.offer(value);
return value;
}
static int consume(){
return bufferQueue.poll();
}
}
public class BufferTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
//Producer Thread
new Thread(
()->{
while(true){
if(Buffer.bufferQueue.size()==Buffer.MAX_SIZE){
try {
System.out.println("Buffer Full");
Thread.sleep(2000);
continue; //Double Check
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("Produced "+Buffer.produce());
}
},"Producer"
).start();
//Consumer Thread
new Thread(
()->{
while(true){
if(Buffer.bufferQueue.size()==0){
try {
System.out.println("Buffer Empty");
Thread.sleep(2000);
continue; //Double check
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("Consumed "+Buffer.consume());
}
},"Consumer"
).start();
}
}