Java和ABAP单例(singleton)设计模式的攻与防

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:


Java和ABAP单例(singleton)设计模式的攻与防

Java和ABAP单例(singleton)设计模式的攻与防Java和ABAP单例(singleton)设计模式的攻与防

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:

Java和ABAP单例(singleton)设计模式的攻与防

And I can still create new instance via reflection:Java和ABAP单例(singleton)设计模式的攻与防

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:

Java和ABAP单例(singleton)设计模式的攻与防

The better solution is to leverage Java Enumeration:

Java和ABAP单例(singleton)设计模式的攻与防

上一篇:Java Socket 网络编程常见异常


下一篇:Spring Cloud(三)《应用服务快速失败熔断降级保护 Hystrix》