Singleton Class
public class SingletonClass {
private static SingletonClass uniqueInstance;
// other variables here
private SingletonClass() { }
public static synchronized SingletonClass getInstance() {
if (uniqueInstance == null)
uniqueInstance = new SingletonClass();
return uniqueInstance;
}
// other methods here
}
class Singleton
ReplyDelete{
private static Singleton instance;
private Singleton(String s)
{
//...
System.out.println("......Instance....." +s);
}
public static synchronized Singleton getInstance(String s)
{
if (instance == null)
instance = new Singleton(s);
return instance;
}
//...
public void doSomething()
{
//...
}
}
public class SingletonClass {
public static void main(String [] args) {
try {
Singleton con = Singleton.getInstance("first"); //ok
}catch(Exception e) {
System.out.println("first: " +e.getMessage());
}
try {
Singleton con2 = Singleton.getInstance("second"); //failed.
}
catch(Exception e) {
System.out.println("second: " +e.getMessage());
}
}
// other methods here
}
Why would the second getInstance() fail?
Delete