i have the following what you might call a lazy loaded singleton per the definition:
public class MySingleton {
public static String myTrigger="a trigger";
private MySingleton(){
}
private static enum LazyLoad {
IMDB_LOOKUP_INSTANCE;
private static final IMDB_LOOKUP = new MySingleton();
}
public static MySingleton getInstance() {
return LazyLoad.IMDB_LOOKUP_INSTANCE.IMDB_LOOKUP;
}
}
What happens when i make a call like this:
String someString = MySingleton.myTrigger;
will the singleton not get instantiated ?
There are issues with your enum. So, i have modified it and the following code works and initializes MySingleton.
public class MySingleton {
public static String myTrigger="a trigger";
private MySingleton(){
System.out.println("Initialized");
}
private static enum LazyLoad {
IMDB_LOOKUP_INSTANCE(new MySingleton());
MySingleton value;
LazyLoad(MySingleton value){
this.value = value;
}
private MySingleton getValue(){
return this.value;
}
}
public static MySingleton getInstance() {
return LazyLoad.IMDB_LOOKUP_INSTANCE.getValue();
}
}
Class gets loaded when you call MySingleton.myTrigger. But if you want your MySingleton to get initialized on class loading, put MySingleton.getInstance() in static block.
After testing (By putting a print statement in the constructor) , I found that -
In the above code, the instantiation will not occur untill the call to MySingleton.getInstance()
But if you put the static MySingleton object as a direct property of the class, instead of inside the enum , it will get instantiated on the call to MySingleton.myTrigger , this is because all static fields are instantiated when the class is loaded.
But in case of enum, enum is not a static property of the class, it is only loaded on access.
I tested something like this as well -
class MySingleton {
public static String myTrigger="a trigger";
private MySingleton(){
System.out.println("Printing");
}
public static enum LazyLoad {
IMDB_LOOKUP_INSTANCE;
public static final String Hello = "Hello";
private static final MySingleton IMDB_LOOKUP = new MySingleton();
}
public static MySingleton getInstance() {
return LazyLoad.IMDB_LOOKUP_INSTANCE.IMDB_LOOKUP;
}
}
In the above , the call to MySingleton.LazyLoad.IMDB_LOOKUP_INSTANCE.Hello would also cause instantiation of MySingleton object.
Your singleton will not get instantiated until you call MySigleton.getInstance().
Related
I have a singleton class that I would like to mock static methods from, so I can test the functionality of the rest of the class. I have created a simpler example to demonstrate. Assume my class that I want to test is this:
public class MockExample {
private static MockExample instance = null;
private static String ourString = "String from main class";
private MockExample() {
}
public static MockExample getInstance() {
if (instance == null) {
instance = new MockExample();
}
return instance;
}
public String getString() {
return getClassString();
}
private static String getClassString() {
return ourString;
}
}
I am trying to mock out MockExample.getClassString() call, my replacing the method with PowerMockito inside the test. It is important to note that that method is private and only gets called through getString(). My test code, with my static mock is below:
public class MockExample {
private static MockExample instance = null;
private static String ourString = "String from main class";
private MockExample() {
}
public static MockExample getInstance() {
if (instance == null) {
instance = new MockExample();
}
return instance;
}
public String getString() {
return getClassString();
}
public static String getClassString() {
return ourString;
}
}
Online examples suggest that if i get the singleton class after I use PowerMockito.replace(method, stub), than it should call the stub. But in this case it is still calling the original method. I have also tried to "spy", but that is proving to be difficult, since my actual code that I need to mock has arguments. PowerMockito.method() handles those well.
Any help would be greatly appreciated. Thank you.
Hi Can please someone tell me the correct way how I can instantiate the below given singleton class?
public class BillPughSingleton {
private BillPughSingleton(){}
private static class SingletonHelper{
private static final BillPughSingleton INSTANCE = new BillPughSingleton();
}
public static BillPughSingleton getInstance(){
return SingletonHelper.INSTANCE;
}
}
Try with:
BillPughSingleton bill = BillPughSingleton.getInstance();
you can rewrite your class simply like this and no more need to SingletonHelper class
public class BillPughSingleton {
private static BillPughSingleton INSTANCE;
private BillPughSingleton(){}
public static BillPughSingleton getInstance(){
if (INSTANCE==null) {
INSTANCE = new BillPughSingleton();
}
return INSTANCE;
}
}
for instansiate you can try this:
BillPughSingleton instance = BillPughSingleton.getInstance();
you can find more another example here
Example class with singleton design pattern.
class Singleton {
private static Singleton instance;
private int x;
private Singleton() {
x = 5;
}
public static synchronized Singleton getInstance() {
if(instance == null) {
instance = new Singleton();
}
return instance;
}
public void doSomething() {
System.out.println("Hello");
}
}
I'm just wondering can I create this class with same variables and methods declared as static. Is it same as the singleton?
Singleton should be considered only if all three of the following criteria are satisfied:
Ownership of the single instance cannot be reasonably assigned
Lazy initialization is desirable
Global access is not otherwise provided for
Yes, It is the same.
If you really need to implement a singelton pattern I would recommend using an enum:
public enum MySingelton{
INSTANCE;
private final String[] variable = new String[]{"test", "test2};
public void randomFunction(){
}
}
Call it with:
MySingelton.INSTANCE.randomFunction();
With an enum implementation it's guaranteed that only one instance is created and that it's available all the time. Also it's possible to serialize and deserialize the singelton without creating multiple copies of it.
More information can be found here:
What is an efficient way to implement a singleton pattern in Java?
http://www.drdobbs.com/jvm/creating-and-destroying-java-objects-par/208403883?pgno=3
Since the purpose of the singleton pattern is to ensure that a single instance of a class exists, yes, you could use static members to achieve the same effect.
So instead of
public class Singleton {
private static Singleton theInstance = new Singleton();
private int aVar = 10;
public void aMethod() {
System.out.println(aVar);
}
public static Singleton getInstance() {
return theInstance;
}
}
you could do
public class FakeSingleton {
private static int aVar = 10;
public static void aMethod() {
System.out.println(aVar);
}
}
and have exactly the same functionality (instead of Singleton.getInstance().aMethod() you would write FakeSingleton.aMethod()).
Using the singleton pattern can be advantageous if you want lazy initialization, so that the singleton is only initialized when it is first needed, as follows:
public class Singleton {
private static Singleton theInstance = null;
private int aVar = 10;
public void aMethod() {
System.out.println(aVar);
}
public static Singleton getInstance() {
if (theInstance == null) {
theInstance = new Singleton();
}
return theInstance;
}
}
(Note that the above is not thread-safe, in multithreaded code you will need to add synchronization.)
Can anyone please tell me whether this is a singleton class or not?
public class Final_output{
Cafe_factory obj=null;
private Final_output()
{
obj = new Cafe_factory();
obj.getOrder("French Fries");
obj.getOrder("Biryani");
obj.getOrder("Ice-cream");
}
public static void main(String args[])
{
new Final_output();
}
}
Cafe_factory is another class in the same package.
This is not a Singleton.
Singleton for Example is:
public class Singleton {
private static final Singleton instance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}
Not, it's not. Because you can't create instances of this class outside of it (at least one instance should exist). For the other hand - you can create as many instances inside main as you wish (so it's not singleton either).
Here is an example of Singleton:
public class MySingleton{
private MySingleton(){}
private static InstanceHolder{
private static final MySingleton instance = new MySingleton();
}
public static MySingleton getInstance(){
return InstanceHolder.instance;
}
}
Its not.
A singleton has as objective to limit to 1 the number of instances of the same class that can be created, and provide static methods to retrieve this instance.
This is typically done via a private constructor and static methods to retrieve this unique instance. Here neither Final_output nor Cafe_factory respect this contract so none of them use the singleton pattern.
Since you could create n amount of new Cafe_Factory objects in your code also outside the Final_output class, no it is not a singleton. A singleton is never created with the new keyword. Instead, you fetch an instance of it via a static method.
this :
public class Final_output{
private static Cafe_factory obj = null;
private Final_output()
{
obj = getCafeInstance();
}
public static getCafeInstance(){
if(null == obj){
obj = new Cafe_factory();
obj.getOrder("French Fries");
obj.getOrder("Biryani");
obj.getOrder("Ice-cream");
}else{
return obj;
}
}
}
NO This is not a singleTon
public class Final_output{
private static Final_output ourInstance = new Final_output();
Cafe_factory obj=null;
private Final_output() {
obj = new Cafe_factory();
obj.getOrder("French Fries");
obj.getOrder("Biryani");
obj.getOrder("Ice-cream");
}
public Final_output getINstance(){
return ourInstance;
}
}
I read a lot on stackoverflow regarding the creation of singleton classes using enum.
I must have missed something because i can't reach the INSTANCE anywhere.
this is my code:
public class UserActivity {
private DataSource _dataSource;
private JdbcTemplate _jdbcTemplate;
static enum Singleton {
INSTANCE;
private static final UserActivity singleton = new UserActivity();
public UserActivity getSingleton() {
return singleton;
}
}
public UserActivity() {
this._dataSource = MysqlDb.getInstance().getDataSource();
this._jdbcTemplate = new JdbcTemplate(this._dataSource);
}
public void dostuff() {
...
}
}
and outside I'm trying to do
UserActivity.INSTANCE.getSingleton()
or
UserActivity.Singleton.
but eclipse's code completion doesn't find anything
thanks!
The trick is to make the enum itself the singleton. Try this:
public enum UserActivity {
INSTANCE;
private DataSource _dataSource;
private JdbcTemplate _jdbcTemplate;
private UserActivity() {
this._dataSource = MysqlDb.getInstance().getDataSource();
this._jdbcTemplate = new JdbcTemplate(this._dataSource);
}
public void dostuff() {
...
}
}
// use it as ...
UserActivity.INSTANCE.doStuff();
INSTANCE is a member of Singleton, not of UserActivity - so you'd need:
UserActivity.Singleton.INSTANCE.getSingleton();
However, you haven't actually made UserActivity a singleton - normally you'd make the type itself an enum, not embed an enum within the type...
public class UserActivity {
private DataSource _dataSource;
private JdbcTemplate _jdbcTemplate;
private static enum Singleton { // private, why not
INSTANCE;
private static final UserActivity singleton = new UserActivity();
public UserActivity getSingleton() {
return singleton;
}
}
private UserActivity() { // private !!(*)
this._dataSource = MysqlDb.getInstance().getDataSource();
this._jdbcTemplate = new JdbcTemplate(this._dataSource);
}
public static UserActivity getInstance() {
return UserActivity.Singleton.INSTANCE.getSingleton();
}
public void dostuff() {
...
}
}
and call UserActivity.getInstance().doStuff();
You can't call the constructor (*) and you can only get an instance of your UserActivity() class via the INSTANCE in the private enum - which is guaranteed to be created once and only once