Search code examples
javaservletscollectionsconcurrencyshopping-cart

Is CopyOnWriteArrayList enough for keeping shopping cart thread-safe in Servlet Session scope


Is CopyOnWriteArrayList list enough to use as a collection for shopping-cart. As I understand it is thread-safe and the iterator is guaranteed not to throw ConcurrentModificationException when during iteration another thread removes a product. For example:

    ...
    CopyOnWriteArrayList<Product> products = (CopyOnWriteArrayList<Product>)session.getAttribute("PRODUCTS");
    products.addIfAbsent(aProduct);
    ...

P.S. I found synchronization approaches using synchronized (session) {...} but it seams a little ugly when I need synchronize session access everywhere when I work with shopping-cart as offered in this article


Solution

  • I think you are good to go with CopyOnWriteArrayList in the scenario you described. It has sufficient guarantees to work as thread safe Implementations including visibility. Yes it is true that it gives the snapshot of the data when you call iterate. But there is always a race condition, while you remove it before reading or read it before removing.CopyOnWriteArrayList is a fine implementation which can be used where reads >>> writes, which i think is the case in shopping cart use case.

    It is just that while iterating you will not see changes (write operation). You should understand nothing is free, if you want to see the changes while traversing you need to properly synchronize your every iteration with any write operation which is will compromise perfomance. Trust me you will gain nothing. Most of the concurrent Data structures gives weakly consistent state on iteration see (ConcurrentSkipListSet). So use either CopyOnWriteArrayList, ConcurrentSkipListSet you are good to go. I think sets are better for your use case i.e to avoid duplicate orders ..