Skip to content

Commit 6cfba5e

Browse files
Update Singleton.java
Singleton can be broken using serialization and reflection. We have to protect our class for that. Check this: https://codippa.com/how-to-break-singleton-in-java/
1 parent 1a0f734 commit 6cfba5e

File tree

1 file changed

+9
-1
lines changed

1 file changed

+9
-1
lines changed

src/create/singleton/Singleton.java

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,10 @@
88
public class Singleton {
99
//防止外部创建实例
1010
private Singleton() {
11-
11+
//To save singleton from reflection
12+
if(mInstance != null) {
13+
throw new InstantiationError("Already there");
14+
}
1215
}
1316
//唯一实例
1417
private static volatile Singleton mInstance;
@@ -25,4 +28,9 @@ public static Singleton getInstance() {
2528
}
2629
return mInstance;
2730
}
31+
32+
//To save singleton from Deserialization
33+
protected Object readResolve() {
34+
return mInstance;
35+
}
2836
}

0 commit comments

Comments
 (0)