title: Groovy(/Java): Lock on unique values of a variable?
body: <p>I have some code in a groovy script where if a graph for a certain name does not exist, I create a new instance of it. </p>
  
  <pre><code>if (!graphMap.contains(graphName)) {
    newGraph = createGraph(graphName)
    graphMap.put(graphName, newGraph)
  }
  </code></pre>
  
  <p>The problem is this is running in parallel and the createGraph() call takes ~60 seconds, so sometimes I'll create 2 instances of the graph and only save 1 of them to my map (because they'll both see the map doesn't contain the name and then create it). It's my understanding that I can lock on the map to avoid this problem, like so:</p>
  
  <pre><code>synchronized(graphMap) {
    if (!graphMap.contains(graphName)) {
      newGraph = createGraph(graphName)
      graphMap.put(graphName, newGraph)
    }
  }
  </code></pre>
  
  <p>But the problem with this is that creating a graph can take a while, and I want to be able to create graphs for several different names at the same time. That is to say, if I get 3 concurrent requests to create graphs for <strong>foo</strong>, <strong>foo</strong>, and <strong>bar</strong>, I want to create <strong>foo</strong> and <strong>bar</strong> concurrently but not create the 2nd <strong>foo</strong>. Is it possible for me to synchronize not on the map, but instead on specific name values?</p>