wood burning stoves*
The moose likes I/O and Streams and the fly likes Serialization Issue with Singleton Class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "Serialization Issue with Singleton Class" Watch "Serialization Issue with Singleton Class" New topic
Author

Serialization Issue with Singleton Class

Souvik Dasgupta
Ranch Hand

Joined: Sep 24, 2009
Posts: 77


Hi All,

I have an query regarding Object Serialization.

I have singleton class Sx and serialize it using standard I/O API. Now if I deserialize it many times, isn't its SINGLETON nature violated?

Thanks and Regards, Souvik
SCJP, SCWCD, OCEJWSD
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19679
    
  18

Unless you prevent that through code, definitely.

Fortunately, you can prevent that, with one simple method: readResolve:
Instead of the object that was found in serialized form, deserializing will now return the result of getInstance(), which is the sole instance of the singleton class.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Souvik Dasgupta
Ranch Hand

Joined: Sep 24, 2009
Posts: 77


Thanks Rob.
I got it.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19679
    
  18

You're welcome.
subba rao k
Greenhorn

Joined: Oct 08, 2013
Posts: 1
Iam new for java . please tell me how to prevent the singleton serialization by using readResolve?
please write the code?
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19679
    
  18

You can't prevent serialization with readResolve(), only maintain the singleton property. If you want to prevent serialization you should just not make the singleton implement Serializable. If that's not possible you can implement writeObject(ObjectOutputStream) or writeReplace() to throw an exception, but that's just a nasty hack.
Muhammad Khojaye
Ranch Hand

Joined: Apr 12, 2009
Posts: 449

ReadResolve is one mechanism used for instance control. In addition, in Java 5 and later versions, ENUM is another approach which guarantees singleton property even in the serialization requirement and reflection attacks.


http://muhammadkhojaye.blogspot.com/
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Serialization Issue with Singleton Class