com.coditory.sherlock.mongo.MongoCollectionInitializer Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of sherlock-mongo Show documentation
Show all versions of sherlock-mongo Show documentation
Distributed Lock Library for JVM
package com.coditory.sherlock.mongo;
import com.mongodb.client.MongoCollection;
import org.bson.Document;
import java.util.concurrent.atomic.AtomicBoolean;
import static com.coditory.sherlock.Preconditions.expectNonNull;
import static com.coditory.sherlock.mongo.MongoDistributedLock.INDEX;
import static com.coditory.sherlock.mongo.MongoDistributedLock.INDEX_OPTIONS;
class MongoCollectionInitializer {
private final MongoCollection collection;
private final AtomicBoolean indexesCreated = new AtomicBoolean(false);
MongoCollectionInitializer(MongoCollection collection) {
expectNonNull(collection, "collection");
this.collection = collection;
}
MongoCollection getInitializedCollection() {
boolean shouldCreateIndexes = indexesCreated.compareAndSet(false, true);
if (!shouldCreateIndexes) {
return collection;
}
collection.createIndex(INDEX, INDEX_OPTIONS);
return collection;
}
}