title: Mongo opens too many connections
body: <p>I am trying to write a lot of data to MongoDB, in a Java loop. I am getting errors based on the number of connections open.</p>
  
  <p>My theory is that since MongoDB is not transactional, lots of connections can be opened simultaneously. However the Java code is also able to loop very fast, after a certain time the number of loop iterations starts overtaking the number of available connections and Mongo hits a wall.</p>
  
  <p>My code looks like this. I've seen it recommended to not do <code>m.close()</code> but then you just get the error even faster.</p>
  
  <pre><code>public static void upsert(){
      Mongo m = null;
      DB db = null;
  
      try {
      m = new Mongo("localhost");
      db = m.getDB("sempedia");    } catch (UnknownHostException e1) { e1.printStackTrace(); } catch (MongoException e1) { e1.printStackTrace(); }
  
      // create documents
      // I am doing an upsert - hence the doc, doc
      DBCollection triples;
  try {
          triples = db.getCollection("triples");
          triples.update(doc,doc,true,false); 
      } catch (MongoException e) { e.printStackTrace(); }
  
      m.close();
  }
  </code></pre>
  
  <p>In my java console I get this error:</p>
  
  <blockquote>
    <p>WARNING: Exception determining maxBSON size using0
    java.net.SocketException: Connection reset</p>
  </blockquote>
  
  <p>And mongodb gives this error:</p>
  
  <blockquote>
    <p>Tue Oct 25 22:31:39 [initandlisten] connection refused because too
    many open connections: 204 of 204</p>
  </blockquote>
  
  <p>What would be the most elegant way to deal with this issue?</p>