Skip to content

Instantly share code, notes, and snippets.

Created January 16, 2015 19:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/5221f3025b549a708299 to your computer and use it in GitHub Desktop.
Save anonymous/5221f3025b549a708299 to your computer and use it in GitHub Desktop.
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ConcurrentUpsertTest {
public static void main(String[] args) {
MongoClient client = new MongoClient();
final DBCollection collection = client.getDB("smoke").getCollection("test");
collection.drop();
ExecutorService executorService = Executors.newFixedThreadPool(5);
// Submit 5 jobs to run concurrently, all upserting a document with the same _id value
for (int i = 0; i < 5; i++) {
executorService.submit(() -> {
while (true) {
try {
collection.update(new BasicDBObject("_id", 2), new BasicDBObject("$inc", new BasicDBObject("x", 1)), true, false);
} catch (Exception e) {
System.err.println(e);
}
}
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment