title: Timed out Exception in Mongodb using Java driver
body: <p>I have the following Java code to save new entry to MongoDB if the entry is not in DB. I run it in Java Timer for every 2 seconds.</p>
  
  <pre><code>        MongoClient mongoClient = null;
          try {
              mongoClient = new MongoClient("localhost", 27017);
          } catch (UnknownHostException e) {
              e.printStackTrace();
          }
  
          DB db = mongoClient.getDB("testdb");
  
          DBCollection coll = db.getCollection("testcollection");
  
          // Search for existing entries
  
          BasicDBObject query = new BasicDBObject("link", entry_url);
  
          DBCursor cursor = coll.find(query);
          try {
              // If it is a new entry, insert
              if (cursor.hasNext() == false) {
                  // Insert new entry
                  BasicDBObject doc = new BasicDBObject("link", entry_url)
                          .append("a_time", accept_time).append(
                                  "p_time", formatter.format(date));
                  coll.insert(doc); 
              }
          } finally {
              cursor.close();
          }
  </code></pre>
  
  <p>The problem is after several minutes, there is a <code>com.mongodb.MongoTimeoutException: Timed out after 10000 ms while waiting to connect. Client view of cluster state is {type=Unknown, servers=[{address=localhost:27017, type=Unknown, state=Connecting}]</code> from mongoDB. It refers to <code>cursor.hasNext()</code>. Any suggestions for this problem?</p>
  
  <pre><code>Exception in thread "Timer-0" com.mongodb.MongoTimeoutException: Timed out after 10000 ms while waiting to connect. Client view of cluster state is {type=Unknown, servers=[{address=localhost:27017, type=Unknown, state=Connecting}]
      at com.mongodb.BaseCluster.getDescription(BaseCluster.java:128)
      at com.mongodb.DBTCPConnector.getClusterDescription(DBTCPConnector.java:396)
      at com.mongodb.DBTCPConnector.getType(DBTCPConnector.java:569)
      at com.mongodb.DBTCPConnector.isMongosConnection(DBTCPConnector.java:370)
      at com.mongodb.Mongo.isMongosConnection(Mongo.java:623)
      at com.mongodb.DBCursor._check(DBCursor.java:494)
      at com.mongodb.DBCursor._hasNext(DBCursor.java:621)
      at com.mongodb.DBCursor.hasNext(DBCursor.java:657)
  </code></pre>
  
  <p>The Timer implementation</p>
  
  <pre><code>         try {
              Timer timer = new Timer();
              timer.schedule(new STimer(), 0, 2 * 1000);
          } catch (Exception e) {
              e.printStackTrace();
          }
  </code></pre>
  
  <p>Based on the comments below, I closed the mongoClient connection. Problem solved.</p>