title: How to write thread safe code in node.js
body: <p>Here's a part of my app.js:</p>
  
  <pre><code>var connections = [];
  
  function removeConnection(res) {
      var i = connections.indexOf(res);
      if (i !== -1) {
          connections.splice(i, 1);
      }
  }
  </code></pre>
  
  <p>And I call removeConnection when a request is closed:</p>
  
  <pre><code>req.on('close', function () {
      console.log("connection closed");
      removeConnection(res);
  });
  </code></pre>
  
  <p>I wonder if the above code is thread safe? I mean as Node.js is event driven, is the following scenario possible?</p>
  
  <ol>
  <li>connections is [a,b,c]</li>
  <li>threadB calls removeConnection</li>
  <li>in threadB.removeConnection: i = 1</li>
  <li>threadA calls removeConnection</li>
  <li>in threadA.removeConnection: i = 0</li>
  <li>in threadA.removeConnection: connections.splice(0, 1); => connections is [b,c]</li>
  <li>in threadA.removeConnection: connections.splice(1, 1); => connections is [b]</li>
  </ol>
  
  <p>As you see in this scenario, threadC's connection would be removed instead of threadB's.</p>
  
  <p>Can this happen? If yes, then how should I fix the code?</p>