Skip to content

Instantly share code, notes, and snippets.

@fernaspiazu
Last active November 14, 2015 01:05
Show Gist options
  • Save fernaspiazu/2e4107e724d0bb5a1365 to your computer and use it in GitHub Desktop.
Save fernaspiazu/2e4107e724d0bb5a1365 to your computer and use it in GitHub Desktop.
A really well done Singleton??? I think it is :-)
/**
* <a href="https://en.wikipedia.org/wiki/Initialization-on-demand_holder_idiom">
* Initialization on-demand Holder idiom.
* </a>
*/
public class MongoDBManager {
private static final String MONGODB_CONNECTION_URL = "mongodb.connection.url";
public static MongoDBManager getInstance() {
return LazyHolder.INSTANCE;
}
private static final class LazyHolder {
static final MongoDBManager INSTANCE = new MongoDBManager();
}
private final MongoClient client;
private MongoDBManager() {
final String connection = getMongoDBProperties().getProperty(MONGODB_CONNECTION_URL);
client = MongoClients.create(new ConnectionString(connection));
}
public MongoClient mongoClient() {
return client;
}
private static Properties getMongoDBProperties() {
try {
InputStream stream = MongoDBManager.class.getResourceAsStream("/data/mongodb.properties");
Properties properties = new Properties();
properties.load(stream);
return properties;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
public class MongoDBManagerTest {
private static final int THREADS = 50;
@Test
public void testConcurrentInstantiation() throws Exception {
ExecutorService executorService = Executors.newFixedThreadPool(THREADS);
long count = Stream.generate(this::mongoDBManagerInstanceTask)
.limit(THREADS)
.parallel()
.map(executorService::submit)
.map(this::completedTask)
.distinct()
.count();
assertThat(count, equalTo(1L));
}
private Callable<MongoDBManager> mongoDBManagerInstanceTask() {
return MongoDBManager::getInstance;
}
private <T> T completedTask(Future<T> future) {
try {
return future.get();
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment