How to properly handle two threads updating the same row in a database
<p>I have a thread called <code>T1</code> for reading a flat file and parsing it. I need to create a new thread called <code>T2</code> for parsing some part of this file and later this <code>T2</code> thread would need to update the status of the original entity, which is also being parsed and updated by the original thread <code>T1</code>.How can I handle this situation?</p>

<p>I receive a flat file having the below sample records:</p>

<pre><code>AAAA
BBBB
AACC
BBCC
AADD
BBDD
</code></pre>

<p>First this file is saved in database in <code>Received</code> status. Now all the records starting with <code>BB</code> or with <code>AA</code> need to be processed in a separate thread. Once it's successfully parsed, both threads will try to update the status of this file object in a database to <code>Parsed</code>. In some cases, I get <code>staleObjectException</code>. <em>Edit: And the work done by any thread before the exception is lost. We are using optimistic locking.</em> What is the best way of avoiding this problem?</p>

<p><a href="https://stackoverflow.com/questions/13374322/possible-hibernate-exceptions-when-two-threads-update-the-same-object">Possible hibernate exceptions when two threads update the same Object?</a></p>

<p>The above post helps to understand some part of it, but it does not help to resolve my problem.</p>