Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a static reference versus a singleton

I am using the java driver for mongodb, and the documentation says to:

"you should create a single Mongo instance, and you can use it in every request."

Using a single instance sounds like a singleton.

In other places for a different library I have read the instructions saying that I should create a static reference as it is thread-safe.

Can someone explain the differences between a singleton and creating a static reference?

So the actual code that I need to instantiate either statically or via a singleton would be:

Mongo m = new Mongo( "localhost" , 27017 );

Can someone explain both methods and the underlying differences if any?

like image 554
codecompleting Avatar asked Dec 02 '11 16:12

codecompleting


1 Answers

In Java you typically use a static variable to implement the Singleton pattern.

http://java.sun.com/developer/technicalArticles/Programming/singletons/

like image 79
JustinKSU Avatar answered Sep 28 '22 06:09

JustinKSU