Singleton concept
Hi,
If i have a singleton object like this:
publicclass MyInstanceextends Thread{
private String myName =null;
privatestatic MyInstance instance =null;
private MyInstance(){
System.out.println("Constructor called");
myName ="MyInstance";
}
publicstaticsynchronized MyInstance getInstance(){
if (null == instance )
instance =new MyInstance();
return instance;
}
publicvoid run(){
System.out.println("Run MyInstance");
synchronized (this){
try{
this.wait();
}catch(Exception e){}
}
}
publicvoid printName(){
System.out.println(myName);
}
}
And it's used like this:
publicclass Test{
/**
* @param args
*/
publicstaticvoid main(String[] args){
// TODO Auto-generated method stub
MyInstance.getInstance().start();
}
}
My question is: if I call "java Test" N times, how many times this line "Constructor called" printed ?
I'm not clear about Singleton, so please help !
KP
[2744 byte] By [
KhanhPhama] at [2007-11-27 2:07:28]

# 1
You are confusing singleton class with a single instance process.
A [url http://www.javaworld.com/javaworld/jw-04-2003/jw-0425-designpatterns.html]singleton[/url] class is a class that only has one instance within a java vm. If you created several java processes(i.e. you run java -cp . YourClass) each would have it's own singleton class.
A single instance is when you start another java running, the new instance communicates with an existing java process and then the new instance quits. See http://mindprod.com/jgloss/singleinstance.html Java WebStart provides this ability through the [url http://java.sun.com/j2se/1.5.0/docs/guide/javaws/jnlp/index.html]SingleInstanceService[/url] I think it should also be available outside of WebStart via a simple mechanism of providing a secondary main. If a class has a secondaryMain(String args[]) then the VM automatically provides a Single Instance. Java has already extended main for agents using a [url http://java.sun.com/j2se/1.5.0/docs/api/java/lang/instrument/package-summary.html]preMain(String args[])[/url]. By googling I found one [url http://www.advancedinstaller.com/user-guide/single-instance-application.html]installer[/url] that provides this functionality.
# 3
hi C..
i had done some experimentation regarding single instance application. as you gain knowledge that providing multiple main methods prevents the behavior.
my approach is how ever create a socket and bind over the application. instantiate application means trying to listening the socket twice which throws SocketBindingException ;-)
let me know your thoughts