Skip to content

Commit d8547e2

Browse files
seanjreillyscotthernandez
authored andcommitted
Closing a Mongo instance now waits for the cleaner
[http://jira.mongodb.org/browse/JAVA-306] Mongo.close() now waits for the DBCleaner thread to finish before returning.
1 parent eabaf7b commit d8547e2

File tree

2 files changed

+40
-4
lines changed

2 files changed

+40
-4
lines changed

src/main/com/mongodb/Mongo.java

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -444,6 +444,12 @@ public List<ServerAddress> getServerAddressList() {
444444
*/
445445
public void close(){
446446
_connector.close();
447+
_cleaner.interrupt();
448+
try {
449+
_cleaner.join();
450+
} catch (InterruptedException e) {
451+
//end early
452+
}
447453
}
448454

449455
/**
@@ -615,7 +621,11 @@ class DBCleanerThread extends Thread {
615621
public void run() {
616622
while (_connector.isOpen()) {
617623
try {
618-
Thread.sleep(cleanerIntervalMS);
624+
try {
625+
Thread.sleep(cleanerIntervalMS);
626+
} catch (InterruptedException e) {
627+
//caused by the Mongo instance being closed -- proceed with cleanup
628+
}
619629
for (DB db : _dbs.values()) {
620630
db.cleanCursors(true);
621631
}

src/test/com/mongodb/MongoTest.java

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,9 @@
1919
package com.mongodb;
2020

2121
import java.io.*;
22-
import java.util.*;
23-
import java.util.regex.*;
2422

23+
import org.testng.annotations.AfterTest;
24+
import org.testng.annotations.BeforeTest;
2525
import org.testng.annotations.Test;
2626

2727
import com.mongodb.util.*;
@@ -34,7 +34,33 @@ public MongoTest()
3434
}
3535

3636
final DB _db;
37-
37+
38+
int _originalCleanerIntervalMs;
39+
40+
@BeforeTest
41+
public void setUp() {
42+
_originalCleanerIntervalMs = Mongo.cleanerIntervalMS;
43+
}
44+
45+
@Test
46+
public void testClose_shouldNotReturnUntilCleanupThreadIsFinished() throws Exception {
47+
48+
System.out.println(Mongo.cleanerIntervalMS);
49+
Mongo.cleanerIntervalMS = 250000; //set to a suitably large value to avoid race conditions in the test
50+
51+
Mongo mongo = new Mongo();
52+
assertNotEquals(mongo._cleaner.getState(), Thread.State.NEW);
53+
54+
mongo.close();
55+
56+
assertFalse(mongo._cleaner.isAlive());
57+
}
58+
59+
@AfterTest
60+
public void tearDown() {
61+
Mongo.cleanerIntervalMS = _originalCleanerIntervalMs;
62+
}
63+
3864
public static void main( String args[] )
3965
throws Exception {
4066
(new MongoTest()).runConsole();

0 commit comments

Comments
 (0)