Reputation: 29816
Question says everything. Is there any special event occurs? I have a class which needs to implement Serializable interface. I am developing an application using Wicket. I have implemented a Factory class which will provide some links (to remove the redundancy of same code block written over and over):
public class NavigationLinkFactory implements Serializable {
private static final long serialVersionUID = 7836960726965363785L;
private NavigationLinkFactory() {
}
private static class SingletonHolder {
public static final NavigationLinkFactory instance = new NavigationLinkFactory();
}
public static NavigationLinkFactory getFactory() {
return SingletonHolder.instance;
}
private Object readResolve() throws ObjectStreamException {
return SingletonHolder.instance;
}
public Link<Serializable> getUserHomeLink() {
return new Link<Serializable>("home", new Model<Serializable>()) {
private static final long serialVersionUID = -8282608926361995521L;
@Override
public void onClick() {
EMSSession session = (EMSSession) getSession();
session.setActiveHorizonalMenu(1);
setResponsePage(HomePage.class);
}
};
}
public Link<Serializable> getProfileLink() {
return getProfileViewLink();
}
public Link<Serializable> getProfileViewLink() {
return new Link<Serializable>("profileView", new Model<Serializable>()) {
private static final long serialVersionUID = 232185489384306999L;
@Override
public void onClick() {
EMSSession session = (EMSSession) getSession();
session.setActiveHorizonalMenu(2);
setResponsePage(ProfileViewPage.class);
}
};
}
}
If I doesn't implement Serializable then I am getting exception at java.io.ObjectOutputStream.writeObject
, which is thrown by the runtime environment of the wicket framework. If I implement it then it is gone.
So what really happens when one calls ObjectInputStream#readobject()
method for some object created by Singleton pattern?
I am not adding wicket tag because I don't think this question is related to the Wicket.
Upvotes: 3
Views: 958
Reputation: 81694
Unfortunately, what happens by default is you get a second (or third, or thirty-seventh) instance of your singleton -- not good. Luckily there's a way around this: by implementing the readResolve() method, which can return a replacement object -- the proper singleton object, in your case -- instead of the one returned by default serialization. The link describes the particulars, but it's pretty simple -- you just implement this parameterless instance method to return the singleton object.
Upvotes: 5
Reputation: 47193
Another way to implement a serialization-safe singleton is by using an enum. See this answer and the links from it. Briefly, the idea is that Java already guarantees that there is only one instance of any given enum value in the JVM, even in the face of serialization, so you can use an enum value as a singleton. It's a hack, but it's a fairly clean hack.
Upvotes: 3