This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Singleton pattern

 
Sugreev Naik
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 8927
Firefox Browser Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Greg Reinl
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4982
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Nicholas Cheung
Ranch Hand
Posts: 4982
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic