I need a threadsafe arraylist like this.
public class BookingList {
private List<Booking> bookings;
public BookingList() {
bookings = Collections.synchronizedList(new ArrayList<Booking>());
}
@Override
public void addBooking(Booking booking)
{
synchronized (bookings) {
bookings.add(booking);
}
}
@Override
public void removeBooking(Booking booking)
{
synchronized (bookings) {
bookings.remove(booking);
}
}
}
According to java doc, when using Collections.synchronizedList one needs to synchronize each access to the list. I'm not sure whether my synchronized blocks will do this?
Is my use of synchronized blocks equivalent to
... public synchronized void addBooking(Booking booking) { bookings.add(booking); }
Should I use a ReentrantLock like this
private Lock lock = new ReentrantLock(); public void addBooking(Booking booking) { try { lock.lock; bookings.add(booking); } finally { lock.release(); } }