wood burning stoves 2.0*
The moose likes OO, Patterns, UML and Refactoring and the fly likes Singleton pattern Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Engineering » OO, Patterns, UML and Refactoring
Bookmark "Singleton pattern" Watch "Singleton pattern" New topic
Author

Singleton pattern

Sugreev Naik
Greenhorn

Joined: Apr 20, 2004
Posts: 1
I have a question regarding singleton pattern. I created a singleton object in my application and wrote it to a file and read it into another object. Here am I not loosing the singleton beaviour? All singleton objects are vulnerable to this problem right ?
Pradeep bhatt
Ranch Hand

Joined: Feb 27, 2002
Posts: 8904

Are you using java serialization for writing it to a file. You can overide the writeObject and readObject methods so that there is only one instance.


Groovy
Greg Reinl
Ranch Hand

Joined: Feb 11, 2003
Posts: 45
To ensure there remains only one instance of the singleton object after deserialization you will need to override the readResolve() method. For one example, see Simply Singleton
Nicholas Cheung
Ranch Hand

Joined: Nov 07, 2003
Posts: 4982
You may add a flag in your singleton object, or create a constructor like this:

Then, for any readObject() and writeObject(), you first create the object, and call its corresponding method to create the object. Thus, you can always has the single object.
Nick


SCJP 1.2, OCP 9i DBA, SCWCD 1.3, SCJP 1.4 (SAI), SCJD 1.4, SCWCD 1.4 (Beta), ICED (IBM 287, IBM 484, IBM 486), SCMAD 1.0 (Beta), SCBCD 1.3, ICSD (IBM 288), ICDBA (IBM 700, IBM 701), SCDJWS, ICSD (IBM 348), OCP 10g DBA (Beta), SCJP 5.0 (Beta), SCJA 1.0 (Beta), MCP(70-270), SCBCD 5.0 (Beta), SCJP 6.0, SCEA for JEE5 (in progress)
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Just a note: The code shown above for creating a singleton is not safe in multi-threaded multi-processor environments. See ...
http://www.javaworld.com/jw-02-2001/jw-0209-double.html
http://www.javaworld.com/javaworld/jw-05-2001/jw-0525-double.html


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Nicholas Cheung
Ranch Hand

Joined: Nov 07, 2003
Posts: 4982
The code I shown is just an idea.
In other to cater for other issues, like threading, multiple access from distributed JVM, etc, you will need extra effort to fulfill those requirements.
Nick
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Singleton pattern
 
Similar Threads
Singleton Pattern
Is StrutsPrepareAndExecuteFilter implemented as singleton pattern to process request
Singleton Pattern
Singleton Connection Class
Why is Singleton needed for thread safety