ICLP c2 Java2
ICLP c2 Java2
programare
JAVA 2
FMI @ UNIBUC
1
The Producer-Consumer Problem
2
The Producer-Consumer Problem
The Producer-Consumer Problem
--------
----------> | BUFFER | --------->
producer -------- consumer
Problem description
Two threads communicate through a buffer (shared memory):
• The Producer “produces” data and puts it in a buffer
• The Consumer takes the data from the buffer and “consumes”
it
Coordination problems
• Producer and consumer should not access the buffer
simultaneously
• Producer must wait if the buffer is full
• Consumer must wait if the buffer is empty
• Producer and Consumer should let each-other know when 3
Buffer interface
4
Implementing the producer
5
Implementing the consumer
6
Synchonization control through the Object class
7
object.wait()
synchronized (obj) {
while (<condition does not hold>)
obj.wait();
... // Perform action appropriate to condition
}
Important
Always enclose obj.wait() in a loop due to spurious wakeup
8
Implementing a buffer of size 1 (close s, i put)
9
Implementing a buffer of size 1 (take)
Note
• Using synchronized methods to prevent simultaneous access
• Using wait guards to block when buffer is full/empty
• Thread is suspended until receiving notify by partener thread
10
A possible main function for Producer-Consumer
11
Possible execution trace
12
BlockingQueue
13
Classes implementing BlockingQueue
14