FileDocCategorySizeDatePackage
ReadersWriterDemo.javaAPI DocExample2601Sun Apr 25 22:35:52 BST 2004None

ReadersWriterDemo

public class ReadersWriterDemo extends Object
Simulate multiple readers
version
$Id: ReadersWriterDemo.java,v 1.5 2004/04/26 02:35:51 ian Exp $

Fields Summary
private static final int
NUM_READER_THREADS
private boolean
done
Set this to true to end the program
private BallotBox
theData
The data being protected.
private ReentrantReadWriteLock
lock
The read lock / write lock combination
Constructors Summary
public ReadersWriterDemo()
Constructor: set up some quasi-random initial data

	
	       	 
	  
		List questionsList = new ArrayList();
		questionsList.add("Agree");
		questionsList.add("Disagree");
		theData = new BallotBox(questionsList);
	
Methods Summary
private voiddemo()
Run a demo with more readers than writers

		
		// Start two reader threads
		for (int i = 0; i < NUM_READER_THREADS; i++) {
			new Thread() {
				public void run() {
					while(!done) {
						Iterator results = null;
						try {
							lock.readLock().lock();
							results = theData.iterator();
						} finally {
							// Unlock in finally to be sure.
							lock.readLock().unlock();
						}
						// Now lock has been freed, take time to print
						print(results);
						try {
							Thread.sleep(((long)(Math.random()* 1000)));
						} catch (InterruptedException ex) {
							// nothing to do
						}
					}
				}
			}.start();
		}
		// Start one writer thread to simulate occasional voting
		new Thread() {
			public void run() {
				while(!done) {
					try {
						lock.writeLock().lock();
						theData.voteFor(
								(((int)(Math.random()*
								theData.getCandidateCount()))));
					} finally {
						lock.writeLock().unlock();
					}
					try {
						Thread.sleep(((long)(Math.random()*1500)));
					} catch (InterruptedException ex) {
						// nothing to do
					}
				}
			}
		}.start();
		
		// In the main thread, wait a while then terminate the run.
		try {
			Thread.sleep(10 *1000);
		} catch (InterruptedException ex) {
			// nothing to do
		} finally {
			done = true;
		}	
	
public static voidmain(java.lang.String[] args)

	     
		new ReadersWriterDemo().demo();
	
private voidprint(java.util.Iterator iter)
print the current totals

		boolean first = true;
		while (iter.hasNext()) {
			BallotPosition pair = (BallotPosition) iter.next();
			if (!first)
				System.out.print(", ");
			System.out.print(pair.getName() + "(" + pair.getVotes() + ")");
			first = false;
		}
		System.out.println();