Note that there are some explanatory texts on larger screens.

plurals
  1. PObest practice for thread safe session bean in spring?
    primarykey
    data
    text
    <p>I'm wondering what is the best practice for making a session bean thread safe.</p> <p>Let's assume I have this session bean and its service:</p> <pre><code>@Component @Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS) class Cart { private HashSet&lt;Item&gt; items = new HashSet&lt;Item&gt;(); private int counter = 0; public HashSet&lt;Item&gt; getItems() { return items; } public int getCounter() { return counter; } } @Service class CartService { @Autowired private Cart cart; public void addItem(Item item) throws FullException { if (cart.getCounter() &gt; 1234) { throw new FullException(); } cart.getItems().add(item); } } </code></pre> <p>The code above is not thread safe and will cause issues when multiple threads (of the same session, eg. by asynchronous Ajax-requests) perform a <code>CartService.addItem(Item)</code>.</p> <p>I think I'm not the first with this problem, but my researches didn't bring me to a best practice.</p> <p>The worst thing I could do would synchronize addItem() as CartService is shared by multiple sessions. Synchronizing on cart in <code>CartService.addItem()</code> seems to me similarly bad, as Cart is a proxied bean. Which I understand as all sessions would still synchronize on the same object.</p> <p>One acceptable solution seems to be a synchronized block on <code>Cart.getItems()</code> in <code>CartService.addItem()</code>:</p> <pre><code>@Service class CartService { @Autowired private Cart cart; public void addItem(Item item) { synchronized(cart.getItems()) { if (cart.getCounter() &gt; 1234) { throw new FullException(); } cart.getItems().add(item); } } } </code></pre> <p>Is there any best practice? Maybe spring has something to offer for this problem?</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