• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Singleton class

 
amarkirt saroay
Ranch Hand
Posts: 167
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can a singleton class be serializable?
 
Campbell Ritchie
Sheriff
Pie
Posts: 49367
62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, but it will no longer be a true singleton.

Singleton ---> same object ---> same object ---> same object ---> serialise ---> deserialise ---> different object
 
Campbell Ritchie
Sheriff
Pie
Posts: 49367
62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Probably not easy enough a question for beginners. Moving.
 
Rob Spoor
Sheriff
Pie
Posts: 20546
56
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:Yes, but it will no longer be a true singleton.

Singleton ---> same object ---> same object ---> same object ---> serialise ---> deserialise ---> different object

That's what the readResolve and writeReplace are for, especially the former:

But Joshua Bloch has given a very good alternative in his "Effective Java" book: use an enum with only one element:
 
Campbell Ritchie
Sheriff
Pie
Posts: 49367
62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Rob. I had quite forgotten about readResolve.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic