You are on page 1of 1

CO3408 Practical 1: Java Synchronisation Primitives

When you have finished this worksheet, you should be able to:
1. Explain the need for synchronisation and mutual exclusion in the producer/consumer problem
2. Explain one problem of busy waiting for synchronisation
3. Use the Java synchronized key word for mutual exclusion
4. Use wait() and notifyAll() to implement synchronization

Activities
Download the zip file containing the producerConsumer source code to your computer.

1. In NetBeans, create a new project.


Choose File, New Project…, Categories: Java with Maven, Projects: Java Application.

In the Projects window, you should see a folder called Source Packages, with an empty package
inside it (the name will depend on the settings you chose). Drag the four .java files from the zip
file (from a file explorer window) into this empty package to import them to the project.

Build the project. The project contains an application that implements a producer/consumer
program. The main program creates two producer threads, two consumer threads and a buffer.
The producers generate items and put them in the buffer, the consumers take them out and
“consume” the items. The threads use the buffer’s insert() and extract() methods. Read
quickly through the program and answer the following questions:
a. What is the purpose of the parameters to the constructors of the producer, the
consumer and the buffer classes?
b. What does the join() method do?
c. How does the buffer keep track of how many items it contains?

2. Run the program and explain its behaviour. You should find that some items are being
consumed twice.

3. Modify the program by using the synchronized key word to ensure mutually exclusive
access to the buffer. Run the program and explain its behaviour. (Hint: you can kill it by
clicking Run, Stop Build/Run or the red stop button in the Output window.

4. Remove the comments around the “wait()” sections and the “notifyAll()” . Run the
program and explain its behaviour. Hint: use the help facilities. Why is the wait() in a loop?
System.err.println("Exception occered "+ex.getMessage());
5. Signals sent os
6. Double the number of items generated by one of the producers. Run the program and explain its
behaviour. Hint: how do the consumers know they have finished?

7. Can you think of a general way of ensuring that the consumers finish when all the items have
been produced?

704709856.doc Page 1 of 1

You might also like