There's much better ways to implement Singleton. Without lazy initialization use declare a static variable and use a static variable initializer to create it:
If you require lazy initialization use an Initialization On Demand Holder:
If you need to perform a more complicated initialization you could use a static initializer (as opposed to a static variable initializer) to do it, just follow the same idiom and instead of using the variable initializer do it in a static block. Lastly, if you need to handle errors or allow them to propogate up through getInstance() from initialization simply go the route of synchronizing the entire getInstance() method:
I also suspect, based on your statement about "sandboxes" and "runs", that you're expecting static variables to be shared across Java processes. They're not. Every time you run a Java program, from the command line, from double-clicking a JAR file, or from choosing "Run..." in Eclipse, you get a new JVM, which is a new OS process, and which has a completely distinct separate set of all variables and data, unrelated to any process before or after.
What is the lifetime of a static variable? It is created when the first time class loaded, and stays there until your application ends.
Joined: Jan 26, 2006
Thanks for all your replies. .I am from the mainframe world, trying to look outside the "well".
By Application I assume every "Run" or "java" command invocation.
I was trying to "Simulate" a multithreaded behaviour by separate runs. Looks like there is no other alternative but to create separate threads from a single class.
I am trying to Sync threads using a static singleton. I am not able to predict any future pitfalls. Can someone suggest if this approach is ok.
Joined: Jul 15, 2003
All the Singleton examples I posted are thread-safe. What you mean by "sync threads by using a static singleton" I'm not sure. There is a threading and synchronization forum here if you have other questions about multithreading.
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com