Java Reference
In-Depth Information
Anytime you wish to synchronize some code, but not an entire method, use the
synchron-
ized
keyword on an unnamed code block within a method, as in:
public void add(Object obj) {
synchronized (someObject) {
// this code will execute in one thread at a time
}
}
The choice of object to synchronize on is up to you. Sometimes it makes sense to synchron-
ize on the object containing the code, as in
Example 22-10
.
For synchronizing access to an
ArrayList
, it would make sense to use the
ArrayList
instance, as in:
synchronized(myArrayList) {
if (myArrayList.indexOf(someObject) != -1) {
// do something with it.
} else {
create an object and add it...
}
}
Example 22-10
is a web servlet that I wrote for use in the classroom, following a suggestion
where the host asks a question and the first person to press her buzzer (buzz in) gets to try to
answer the question correctly. To ensure against having two people buzz in simultaneously,
the code uses a synchronized block around the code that updates the Boolean
buzzed
vari-
able. And for reliability, any code that accesses this Boolean is also synchronized.
Example 22-10. BuzzInServlet.java
public
public class
class
BuzzInServlet
BuzzInServlet
extends
extends
HttpServlet
{
/** The attribute name used throughout. */
protected
protected final
final static
static
String WINNER
=
"buzzin.winner"
;
/** doGet is called from the contestants web page.
* Uses a synchronized code block to ensure that
* only one contestant can change the state of "buzzed".
*/
public
public
void
void
doGet
(
HttpServletRequest request
,
HttpServletResponse response
)
throws
throws
ServletException
,
IOException
{