• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Singletons and Serializable

 
Ranch Hand
Posts: 529
C++ Java Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Folks,

Maybe not a Java puzzler, but here goes.

I have a Singleton class X. So that supposedly guarantees only 1 instance per JVM right? But then I have a state manager class that manages the persistence of certain classes based on options and such. One of the classes it serializes is class X. When the program starts again, class X is loaded from disk. Now I am no longer guaranteed only 1 instance. Now I can potentially have 2 instances floating around, the one that was loaded and if someone calls getX(). That is because my static variable in X is still null.

Now I can easily create a method public static void setX(X x); and call it from the state manager class when X is loaded. But I am sensing a design flaw. I could also put my persistence code in X, but then I would have duplicate code and I really like the idea of having all of my persistence handled in 1 place. Is there a pattern that handles this sort of issue?


many thanks,

Barry
 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yep. It's the DontMakeSingletonClassesSerializable pattern! Don't make them Cloneable, either.
 
Ranch Hand
Posts: 2937
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If your singleton is serializable, it must have a readResolve() method that looks like this:

 
What could go wrong in a swell place like "The Evil Eye"? Or with this tiny ad?
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic