Categories
Java

Synchronizing Reader and Writer Threads

Here are two functions that you should use when you want two threads, producer and consumer, to be synchronized. I used these functions mainly to ensure that the reader will stop until an object is ready to read. An advantage is that you can control how many objects are in memory at the same time.

 
protected List<Object> availableObjects = new ArrayList<Object>();
 
/**
 * Delivers the next object.
 * Used by the reader/consumer thread.
 */
public synchronized Object next() {
	Object rc;
 
	while (availableObjects.isEmpty()) {
		try {
			wait();
		} catch (InterruptedException e) { }
	}
	rc = availableObjects.remove(0);
 
	notify();
 
	return rc;
}
 
/**
 * Adds a new object to the list of available objects.
 * Used by the writer/producer thread.
 */
public synchronized void addObject(Object o) {
	while (availableObjects.size() >= 20) {
		try {
			wait();
		} catch (InterruptedException e) {}
	}
	availableObjects.add(o);
 
	notify();
}

The main idea was taken from Silberschatz’ book about Operating Systems. You have to make sure that you never call the next() method when the last object was read. So be careful when your number of objects produced is limited.

Leave a Reply

Your email address will not be published. Required fields are marked *