Skip to content

Commit c624de0

Browse files
committed
Always close connections
1 parent aabfc11 commit c624de0

File tree

1 file changed

+20
-18
lines changed

1 file changed

+20
-18
lines changed

java/src/main/java/com/start/Connection.java

Lines changed: 20 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -49,31 +49,33 @@ public static void main(String[] args) throws ParseException {
4949
mongoClient = MongoClients.create(uri);
5050
}
5151

52-
MongoDatabase database = mongoClient.getDatabase("test");
52+
try {
53+
MongoDatabase database = mongoClient.getDatabase("test");
5354

54-
Document command = new Document("ping", 1);
55-
Document res = database.runCommand(command);
55+
Document command = new Document("ping", 1);
56+
Document res = database.runCommand(command);
5657

57-
assert res.getDouble("ok").equals(1.0) : "ping failed";
58+
assert res.getDouble("ok").equals(1.0) : "ping failed";
5859

59-
command = new Document("dropDatabase", 1);
60-
res = database.runCommand(command);
60+
command = new Document("dropDatabase", 1);
61+
res = database.runCommand(command);
6162

62-
assert res.getDouble("ok").equals(1.0) : "dropDatabase failed";
63+
assert res.getDouble("ok").equals(1.0) : "dropDatabase failed";
6364

64-
List<Document> docList = new ArrayList<Document>(4);
65-
docList.add(new Document("_id", 1).append("a", 1));
66-
docList.add(new Document("_id", 2).append("a", 2));
67-
docList.add(new Document("_id", 3).append("a", 3));
68-
docList.add(new Document("_id", 4).append("a", 4));
65+
List<Document> docList = new ArrayList<Document>(4);
66+
docList.add(new Document("_id", 1).append("a", 1));
67+
docList.add(new Document("_id", 2).append("a", 2));
68+
docList.add(new Document("_id", 3).append("a", 3));
69+
docList.add(new Document("_id", 4).append("a", 4));
6970

70-
MongoCollection<Document> collection = database.getCollection("foo");
71-
collection.insertMany(docList);
71+
MongoCollection<Document> collection = database.getCollection("foo");
72+
collection.insertMany(docList);
7273

73-
Document actual = collection.find(eq("a", 4)).first();
74-
assert actual.equals(new Document("_id", 4).append("a", 4)) : "Value should be 4";
75-
76-
mongoClient.close();
74+
Document actual = collection.find(eq("a", 4)).first();
75+
assert actual.equals(new Document("_id", 4).append("a", 4)) : "Value should be 4";
76+
} finally {
77+
mongoClient.close();
78+
}
7779

7880
// quick way to kill driver's background threads
7981
// and prevent hanging for a long time

0 commit comments

Comments
 (0)