Win a copy of Java 9 Revealed this week in the Features new in Java 9 forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Singleton class  RSS feed

 
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
Posts: 54030
130
  • 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
Posts: 54030
130
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Probably not easy enough a question for beginners. Moving.
 
Rob Spoor
Sheriff
Posts: 20940
81
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
Posts: 54030
130
  • 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
Boost this thread!