Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Firstly I'm assuming that you meant to say that the <code>Cart</code> bean is Session scoped (your example says that it is request scoped, but that doesn't seem to make sense) and that <code>CartService</code> is a singleton.</p> <p>If we think about how your user interacts with the application, do we actually have a need to perform any synchronization on a <code>Cart</code> instance?</p> <p>We definitely do not need to make <code>CartService.addItem()</code> synchronized as we're relying on Spring's proxy injection to ensure that the <code>Cart</code> instance from the current Session is injected during the Thread of execution, so no worries there.</p> <p>So our question of synchronization is about whether there is a scenario during a single Session that requires us to synchronize adding of items to a <code>Cart</code>? </p> <p>I assume that your Session is being driven by the user's browser. There is no way legitimate way to share a single Session between different browsers. So apart from having multiple tabs open, it is highly likely that your user will be adding items to their <code>Cart</code> in a sequential manner. Even if they did open multiple tabs and enter items is there a problem? Once the user initiates your "checkout" process, you can block adding more items to the <code>Cart</code> and then ask the user to confirm that the <code>Cart</code> they are about to checkout is correct, giving them the opportunity to remove any dubious items.</p> <p>If you still decide that you really need synchronization on the <code>Cart</code> then I would do the following:</p> <pre><code>public class Cart { private HashSet&lt;Item&gt; items = new HashSet&lt;Item&gt;(); public synchronized void addItem(Item item) { items.add(item); } } </code></pre> <p>That way you easily synchronize access to the <code>Set</code> within the <code>Cart</code> class.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload