forked from mongodb/mongo-java-driver
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMultiThreadedExample.java
More file actions
66 lines (57 loc) · 2.52 KB
/
Copy pathMultiThreadedExample.java
File metadata and controls
66 lines (57 loc) · 2.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package example;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.ReadPreference;
import java.net.UnknownHostException;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* An example of using a MongoClient in a multi-threaded environment.
*
* It runs in a console until Ctrl-C. It takes an optional command line argument for the URI to use to connect.
*/
public class MultiThreadedExample {
public static final int NUM_DOCUMENTS = 10000;
public static final int NUM_THREADS = 100;
public static void main(String[] args) throws UnknownHostException {
MongoClientURI uri = args.length > 0
? new MongoClientURI(args[0])
: new MongoClientURI("mongodb://localhost");
MongoClient mongoClient = new MongoClient(uri);
DB db = mongoClient.getDB(uri.getDatabase() != null
? uri.getDatabase()
: "test");
final DBCollection collection = db.getCollection("test");
collection.drop();
ExecutorService executorService = Executors.newFixedThreadPool(NUM_THREADS);
for (int i = 0; i < NUM_THREADS; i++) {
executorService.submit(new Runnable() {
@Override
public void run() {
Random random = new Random();
while (true) {
int i = random.nextInt(NUM_DOCUMENTS);
try {
DBObject document = collection.find(new BasicDBObject("i", i))
.setReadPreference(ReadPreference.secondaryPreferred())
.one();
if (document == null) {
collection.insert(new BasicDBObject("i", i));
} else {
collection.update(new BasicDBObject("_id", document.get("_id")),
new BasicDBObject("$set", new BasicDBObject("i", i + 1)));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
}
}
}