title: Java threads locking on a specific object
body: <p>I have a web application and I am using Oracle database and I have a method basically like this:</p>
  
  <pre><code>public static void saveSomethingImportantToDataBase(Object theObjectIwantToSave) {
        if (!methodThatChecksThatObjectAlreadyExists) {
           storemyObject() //pseudo code
       }
       // Have to do a lot other saving stuff, because it either saves everything or nothing
       commit() // pseudo code to actually commit all my changes to the database.
  }
  </code></pre>
  
  <p>Right now there is no synchronization of any kind so n threads can of course access this method freely, the problem arises when 2 threads enter this method both check and of course there is nothing just yet, and then they can both commit the transaction, creating a duplicate object.</p>
  
  <p>I do not want to solve this with a unique key identifier in my Database, because I don't think I should be catching that <code>SQLException</code>.</p>
  
  <p>I also cannot check right before the commit, because there are several checks not only <code>1</code>, which would take a considerable amount of time.</p>
  
  <p>My experience with locks and threads is limited, but my idea is basically to lock this code on the object that it is receiving. I don't know if for example say I receive an Integer Object, and I lock on my Integer with value 1, would that only prevent threads with another Integer with value 1 from entering, and all the other threads with <code>value != 1</code> can enter freely?, is this how it works?.</p>
  
  <p>Also if this is how it works, how is the lock object compared? how is it determined that they are in fact the same object?. A good article on this would also be appreciated. </p>
  
  <p>How would you solve this?.</p>