I have a following test
@Test
public void testPutDocuments() throws Exception {
final DBObject document01 = new DBObject();
document01.put("uniqueId", "001");
document01.put("rv", "values");
document01.put("pv", "values");
final DBObject document02 = new DBObject();
document02.put("uniqueId", "002");
document02.put("rv", "values");
document02.put("pv", "values");
final DBObject document03 = new DBObject();
document03.put("uniqueId", "003");
document03.put("rv", "values");
document03.put("pv", "values");
final List<DBObject> documents = new ArrayList<DBObject>();
documents.add(document01);
documents.add(document02);
documents.add(document03);
mongoRule.getMongoService().putDocuments(documents);
assertEquals(3, mongoRule.getDatabase().getCollection("test").getCount());
}
Where mongoRule
is a rule which connects to database, provides MongoService
(a wrapper written to mongo client)
MongoService related methods
public void putDocument(@Nonnull final DBObject document) {
LOGGER.info("inserting document - " + document.get("uniqueId"));
mongo.getDB(database).getCollectionFromFull(getCollectionName(document)).insert(document);
}
public void putDocuments(@Nonnull final List<DBObject> documents) {
for (final DBObject document : documents) {
putDocument(document);
}
}
When I run this, I get
java.lang.AssertionError:
Expected :3
Actual :1
Now, if I do this
mongoRule.getMongoService().putDocuments(documents);
Thread.sleep(1000);
assertEquals(3, mongoRule.getDatabase().getCollection("contract").getCount());
I see no error.
Question:
a.) Why sleeping a thread for a second helped in getting a right number. isn't it a concurrency related issue? What if two threads are trying to put same documents where as document has to be unique.
b.) How can I fix this?
Thank you