• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Serialization Issue with Singleton Class

 
Souvik Dasgupta
Ranch Hand
Posts: 95
Eclipse IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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?
 
Rob Spoor
Sheriff
Pie
Posts: 20493
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Souvik Dasgupta
Ranch Hand
Posts: 95
Eclipse IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Thanks Rob.
I got it.
 
Rob Spoor
Sheriff
Pie
Posts: 20493
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome.
 
subba rao k
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Iam new for java . please tell me how to prevent the singleton serialization by using readResolve?
please write the code?
 
Rob Spoor
Sheriff
Pie
Posts: 20493
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 449
IntelliJ IDE Java Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic