Logo 
Search:

Java Answers

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds
  Question Asked By: Oscar Montgomery   on Oct 09 In Java Category.

  
Question Answered By: Caitlin Brown   on Oct 09

Your singleton is not thread safe...

either you need to synchronize the getInstance method or maybe you should
initialize it in the declaration of the MySingleTon variable instead?

Also you dont have to use static when using a singleton (after all the
MySingleTon var is already static) do all your initialization in
the constructor of the singleton instead. This is the template i use (may
contain typoes since i just need to sleep instead of compiling but since
sleeping is boring, im here typing this message... oh well):

class Singleton {
private static Singleton _inst = new Singleton();
public Singleton getInstance() {
return _inst;
}

// Other props
private int aValue;
private String anotherOne;

// constructor - initializes
private Singleton() {
aValue = 5;
anotherOne = "five";
// etc
}

public synchronized void setAValue(int val) {
aValue = val;
}
public int getAValue() {
return aValue;
}
}

Note that the only member being static is the instance of the Singleton,
everything else should not be. If you have methods (e,g, setters) for
updating data in the singleton you MUST synchronize them or you may have
problems.

My singleton can be tested like this:

Singleton s1 = Singleton.getInstance();
s1.setAValue(7);
/* now lets drop s1 and get a completely new instance... um or is it? ;) */
Singleton s2 = Singleton.getInstance();
System.out.println( s2.getAValue() );
// and we should get a nice 7, not a 5 or anything else

I'd also like to raise a warning here. Singletons are not always a good
solution to your problems, in an EJB environment they may cause more harm
than help since a singleton is specific to it's classloader by default and
EJB uses several classloaders even several machines thus making strange
things happening to some singletons.

For your property loader class you could also check out
java.util.ResourceBundle especially if you want to work with multi language
content.

Share: 

 

This Question has 4 more answer(s). View Complete Question Thread

 
Didn't find what you were looking for? Find more on Report of Daffodi DB Or get search suggestion and latest updates.


Tagged: