Producer/Consumer Relationshipwithout Synchronization
}In a producer/consumer relationship, the producer portion of an application generates data and stores it in a shared object, and the consumer portion of the application reads data from the shared object.
}A producer thread generates data and places it in a shared object called a buffer.}A consumer thread reads data from the buffer.
}This relationship requires synchronization to ensure that values are produced and consumed properly.
}Operations on the buffer datashared by a producer and consumer thread are also state dependent—the operations should proceed onlyif the buffer is in the correct state.
}If the buffer is in a not-fullstate, the producer may produce; if the buffer is in a not-empty state, theconsumer may consume.
Producer/Consumer Relationship: ArrayBlockingQueue
}One way to synchronize producer and consumer threads is to use classes from Java’s concurrency package that encapsulate the synchronization for you.
}Java includes the class ArrayBlockingQueue-(from package java.util.concurrent)—a fully implemented, thread-safebuffer class that implements interface BlockingQueue.
}Declares methods put and take, the blocking equivalents of Queuemethods offer and poll, respectively.
}Method put places an element at the end of the BlockingQueue, waiting if the queue is full.
}Method take removes an element from the head of the BlockingQueue, waiting if the queue is empty.
Producer/Consumer Relationshipwith Synchronization
}For educational purposes, we now explain how you can implement a shared buffer yourself using the synchronized keyword and methods of class Object.
}The first step in synchronizingaccess to the buffer is to implement methods get and set as synchronized methods.
}This requires that a thread obtain the monitor lock on the Buffer object before attempting to access the buffer data.
}Object methods wait, notify and notifyAll can be used with conditions to make threads wait when they cannot perform their tasks.
}Calling Object method wait on a synchronized object releases its monitor lock, and places the calling thread in the waiting state.
}Call Object method notify on a synchronized object allows a waiting thread totransition to the runnable state again.
}If a thread calls notifyAll on the synchronized object, then all the threads waiting for the monitor lock become eligible to reacquire the lock.
.

