Java Reference
In-Depth Information
To demonstrate
ReadWriteLock
in action, I wrote the business logic portion of a web-based
voting application. It could be used in voting for candidates or for the more common web
poll. Presuming that you display the results on the home page and change the data only when
somebody takes the time to click a response to vote, this application fits one of the intended
criteria for
ReadWriteLock
—i.e., that you have more readers than writers. The main class,
simply keeps track of the votes and returns a read-only
Iterator
upon request. Note that in
the
run( )
method of the reading threads, you could obtain the iterator while holding the
lock but release the lock before printing it; this allows greater concurrency and better per-
formance, but could (depending on your application) require additional locking against con-
current update.
Example 22-11. ReadersWriterDemo.java
public
public class
class
ReadersWriterDemo
ReadersWriterDemo
{
private
private static
static final
final
int
int
NUM_READER_THREADS
=
3
;
public
public static
static
void
void
main
(
String
[]
args
) {
new
new
ReadersWriterDemo
().
demo
();
}
/** Set this to true to end the program */
private
private volatile
volatile
boolean
boolean
done
=
false
false
;
/** The data being protected. */
private
private
BallotBox theData
;
/** The read lock / write lock combination */
private
private
ReadWriteLock lock
=
new
new
ReentrantReadWriteLock
();
/**
* Constructor: set up some quasi-random initial data
*/
public
public
ReadersWriterDemo
() {
List
<
String
>
questionsList
=
new
new
ArrayList
<>();
questionsList
.
add
(
"Agree"
);
questionsList
.
add
(
"Disagree"
);
questionsList
.
add
(
"No opinion"
);
theData
=
new
new
BallotBox
(
questionsList
);
}
/**
* Run a demo with more readers than writers
*/