Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you have concurrency issues, just adding 'volatile' probably won't help you.</p> <p>As for keeping the object as an attribute of Session, I'd recommend you to keep just the object's ID, and use it to retrieve a 'live' instance when you need it (if you use Hibernate, successive retrieves will return the same object, so this shouldn't cause performance problems). Encapsulate all modification logic to this specific object into a single façade, and do the control concurrency there, using dababase locking.</p> <p>Or, if you really, really, really want to use memory-based locking, and are really sure that you'll never have two instances of the application running in a cluster, make sure that your façade logic is synchronized at the right level. If your synchronization is too fine grained (low-level operations, <em>such as volatile variables</em>), it probably won't be enough to make your code thread-safe. For example, <code>java.util.Hashtable</code> is fully synchronized, but it doesn't mean anything if you have logic like this:</p> <pre><code>01 if (!hashtable.containsKey(key)) { 02 hashtable.put(key, calculate(key)); 03 } </code></pre> <p>If two threads, say, <code>t1</code> and <code>t2</code>, hit this block at the same time, <code>t1</code> may execute line <code>01</code>, then <code>t2</code> may also execute <code>01</code>, and then <code>02</code>, and <code>t1</code> then will execute <code>02</code>, overwriting what <code>t2</code> had done. The operations <code>containsKey()</code> and <code>put()</code> are atomic individually, but what should be atomic is the whole block.</p> <p>Sometimes recalculating a value doesn't matter, but sometimes it does, and it <em>will</em> break.</p> <p>When it comes to concurrency, there's no magic. I mean, <strike>seam</strike> some crappy frameworks try to sell you the idea that they solve this problem for you. They don't. Even if it works 99% of the time, it will break spectacularly when you go to production and start to get heavy traffic. Or (much, much) worse, it will silently generate wrong results.</p> <p>Concurrency is one of the most complex problems in programming. And the only way to handle it is to avoid it. All this functional programming trend is not about dealing with concurrency, is about avoiding it altogether.</p>
 

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