title: Synchronizing on an Integer value
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/12890586/what-is-the-best-way-to-increase-number-of-locks-in-java">What is the best way to increase number of locks in java</a>  </p>
  </blockquote>
  
  
  
  <p>Suppose I want to lock based on an integer id value. In this case, there's a function that pulls a value from a cache and does a fairly expensive retrieve/store into the cache if the value isn't there.</p>
  
  <p>The existing code isn't synchronized and could potentially trigger multiple retrieve/store operations:  </p>
  
  <pre><code>//psuedocode
  public Page getPage (Integer id){
     Page p = cache.get(id);
     if (p==null)
     {
        p=getFromDataBase(id);
        cache.store(p);
     }
  }
  </code></pre>
  
  <p>What I'd like to do is synchronize the retrieve on the id, e.g. </p>
  
  <pre><code>   if (p==null)
     {
         synchronized (id)
         {
          ..retrieve, store
         }
     }
  </code></pre>
  
  <p>Unfortunately this won't work because 2 separate calls can have the same Integer id value but a different Integer object, so they won't share the lock, and no synchronization will happen. </p>
  
  <p>Is there a simple way of insuring that you have the same Integer instance? For example, will this work:</p>
  
  <pre><code> syncrhonized (Integer.valueOf(id.intValue())){
  </code></pre>
  
  <p>The javadoc for Integer.valueOf() seems to imply that you're likely to get the same instance, but that doesn't look like a guarantee:</p>
  
  <blockquote>
    <p>Returns a Integer instance
    representing the specified int value.
    If a new Integer instance is not
    required, this method should generally
    be used in preference to the
    constructor Integer(int), as this
    method is likely to yield
    significantly better space and time
    performance by caching frequently
    requested values.</p>
  </blockquote>
  
  <p>So, any suggestions on how to get an Integer instance that's guaranteed to be the same, other than the more elaborate solutions like keeping a WeakHashMap of Lock objects keyed to the int? (nothing wrong with that, it just seems like there must be an obvious one-liner than I'm missing).</p>