Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Producer consumer thread problem.

 
Tony Evans
Ranch Hand
Posts: 598
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Run I run my application both threads block. The consumer blocks waiting to be notified. The Producer every time it carrys out an action calls notifyAll(), this does not wake up the consumer thread, I guess that even though it has called notifyAll it still has the lock. It only releases the lock on a wait.



When it can no longer produce it goes into a wait state so both threads are waiting.

synchronized void produce(){
Date message;
while(true){
System.out.println("Producer produce "+buffer.getBufferSize());
SleepUtilities.nap();
message = new Date();
try {
if(buffer.getBufferSize() < buffer.getBufferLength()){
buffer.insert(message);
// As well as calling notifyAll what else can I do here
notifyAll();
}else{
wait();
}

}catch(InterruptedException e){
System.out.println("Producer "+e);
}
}
}

synchronized public void consume(){
Date message;
while(true) {
System.out.println("Consumer consume "+buffer.getBufferSize());
SleepUtilities.nap();
try {
if(buffer.getBufferSize() > 0) {
message = (Date)buffer.remove();
System.out.println("Consumer consume call notify");
notifyAll();

} else {
System.out.println("Consumer consume Enter wait state");
wait();
}
}catch(InterruptedException e){
System.out.println("Consumer "+e);
}
}
}

Thanks for any help
 
Tony Evans
Ranch Hand
Posts: 598
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Fixed to use synchronized wait and notify it must be on the same object. Instead of the producer and consumer it should of been on my boundedBuffer insert remove methods.

public synchronized void insert(Object item) throws InterruptedException{
if(nextFreePostion > BUFFER_SIZE){
wait();
}
System.out.println("Insert "+item+" into Buffer");
buffer[nextFreePostion] = item;
nextFreePostion = (nextFreePostion+1) %BUFFER_SIZE;
bufferSize++;
notifyAll();
}

public synchronized Object remove() throws InterruptedException{
if(nextFullPostion == 0){
wait();
}
Object item = buffer[nextFullPostion];
System.out.println("Remove "+item+" from Buffer");
nextFullPostion = (nextFullPostion+1) %BUFFER_SIZE;
bufferSize--;
notifyAll();
return item;
}
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic