Hi,
The "connectionsPerHost" is the maximum number of connections per mongod/mongos process that the driver will open (note in this case we mean per host AND port combinations).
So in the following code sample that follows :
- the contested method will eventually open 25 connections to the mongod instance.
- the uncontested method will eventually open 50 connection to the mongod instance.
Both methods create 1000 objects in the collection but because the threads are blocked trying to get a connection from the pool in the contested case, the code takes about twice as long to run (at least for me).
Regards,
-Jim
import com.mongodb.*;
import java.net.UnknownHostException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
public class App
{
public static void main( String[] args )
{
try {
long c = contested();
long u = uncontested();
System.out.println("contested took " + c);
System.out.println("uncontested took " + u);
} catch (Exception e) {
e.printStackTrace();
}
}
public static long contested() throws InterruptedException, UnknownHostException {
int conns = 50;
MongoClientOptions.Builder builder = new MongoClientOptions.Builder().writeConcern(WriteConcern.ACKNOWLEDGED);
builder.connectionsPerHost(conns / 2);
return create(conns, 10000, builder.build());
}
public static long uncontested() throws InterruptedException, UnknownHostException {
int conns = 50;
MongoClientOptions.Builder builder = new MongoClientOptions.Builder().writeConcern(WriteConcern.ACKNOWLEDGED);
return create(conns, 10000, builder.build());
}
public static long create(int conns , int total, MongoClientOptions opts) throws InterruptedException, UnknownHostException {
final AtomicInteger max = new AtomicInteger(total);
final CountDownLatch start = new CountDownLatch(1);
final CountDownLatch finish= new CountDownLatch(conns);
ServerAddress sa = new ServerAddress("localhost", 27017);
MongoClient mongoClient = new MongoClient( sa ,opts);
DB db = mongoClient.getDB( "test" );
final DBCollection collection = db.getCollection("gg");
collection.drop();
for (int i =0 ; i < conns; i++)
{
new Thread(new Runnable() {
public void run() {
try
{
start.await();
while (max.decrementAndGet() >= 0)
{ long ts = System.currentTimeMillis(); collection.insert(BasicDBObjectBuilder.start().append("name", Thread.currentThread().toString() ).append("ts", ts ).get()); }
}
catch (Exception e)
{ e.printStackTrace(); }
finally { finish.countDown(); }
}
}).start();
}
long s = System.currentTimeMillis();
start.countDown();
finish.await();
return (System.currentTimeMillis() - s );