Reputation: 808
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.
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();
}
The problem is after several minutes, there is a 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}]
from mongoDB. It refers to cursor.hasNext()
. Any suggestions for this problem?
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)
The Timer implementation
try {
Timer timer = new Timer();
timer.schedule(new STimer(), 0, 2 * 1000);
} catch (Exception e) {
e.printStackTrace();
}
Based on the comments below, I closed the mongoClient connection. Problem solved.
Upvotes: 0
Views: 5153