Java Reference
In-Depth Information
Controlling bean concurrency
As you might have noticed, the bean includes a
@Lock
annotation on top of the methods
managing our collection of
Seat
objects. This kind of annotation is used to control the
concurrency of the singleton.
Concurrent access to a singleton EJB is, by default, controlled by the container. Read/write
access to a singleton is limited to one client at a time. However,it is possible to provide a
finer level of concurrency control through the use of annotations. This can be achieved us-
ing the
@Lock
annotation, whose arguments determine the type of concurrency access per-
mitted.
By using a
@Lock
annotation of type
javax.ejb.LockType.READ
, multithreaded ac-
cess will be allowed to the bean. This is shown in the following code:
@Lock(READ)
public Collection<Seat> getSeats() {
return
Collections.unmodifiableCollection(seats.values());
}
On the other hand, if we apply
javax.ejb.LockType.WRITE
, the single-threaded ac-
cess policy is enforced, as shown in the following code:
@Lock(WRITE)
public void buyTicket(int seatId) throws
SeatBookedException, NoSuchSeatException {
final Seat seat = getSeat(seatId);
if (seat.isBooked()) {
throw new SeatBookedException("Seat " + seatId +
" already booked!");
}
addSeat(seat.getBookedSeat());
}
The general idea is to use
READ
type locks on methods that just read values from the cache
and
WRITE
type locks for methods that change the values of elements contained in the
cache. Keep in mind that
WRITE
type locks block all methods with
READ
type locks. It is
crucial that the singleton will have exclusive control of the modifications of its state. Lack