0

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?

  1. Is my use of synchronized blocks equivalent to

    ...
    public synchronized void addBooking(Booking booking) {
      bookings.add(booking);
    }
    
  2. 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();
      }
    }
    
4

2 回答 2

6

您不需要同步添加删除简单操作,因为这是由实现在内部处理的,这正是您使用它们的原因:避免自己处理同步

但是对于超出内部同步范围的迭代多次删除复合操作,您必须提供自己的锁定机制。

于 2013-06-20T13:47:19.107 回答
3

要回答您的问题:

1:

public synchronized void addBooking(Booking booking) {
   bookings.add(booking);
}

相当于

public void addBooking(Booking booking) {
   synchronized (this){
       bookings.add(booking);
   }
}

2:对于您的示例,您不应使用ReentrantLock. 调用已初始化列表的方法Collections.synchronizedList()是线程安全的,无需synchronized使用进一步或其他锁定机制。其余的请参见@Pragmateek 的回答。

于 2013-06-20T13:52:37.317 回答