Recently I meet with an issue using Spring which finally turns out that my bean is initialized multiple times although it is expected to be a singleton. As a result I look into the possible scenario that might bypass the expected singleton behavior.
This blog introduces two possible scenarios which will cause your singleton design fail to work as expected.
This is my singleton class in ABAP:
Via comparison in debugger we can know that the instance got from deserialization is a different instance from the original one returned by GET_INSTANCE.
[图片]
In Java it is even not necessary to use this approach to bypass the singleton. It is enough to just use reflection.
This is my singleton class:
And I can still create new instance via reflection:
finally I get false in console.
In Java this bypass action could be defended by using a boolean variable to detect whether the constructor has already been executed or not. If the constructor is called with value equals to true, it means the constructor has been executed repeatedly, then we raise exception.
The source code of improved singleton is listed below:
The better solution is to leverage Java Enumeration: