当前位置:网站首页>Detailed single case mode
Detailed single case mode
2022-06-30 18:52:00 【Z boo boo】
List of articles
- The singleton pattern
- 1. Hungry han singleton
- 2. An example of lazy style
- 3. Static inner class gets the singleton
- 4. Reflection breaking singleton mode
- Normal acquisition
- Broken ring one : A single instance is obtained in the normal way , A single instance is obtained by reflection
- Broken ring II , Create objects without using the references provided in the class , Every time you create an object, you use the reflection method
- Broken ring three , By breaking the fields in the class , Destroy the traffic light strategy
- 5. The way to enumerate , Prevent single cases from being destroyed
The singleton pattern
1. Hungry han singleton
characteristic : First, instantiate the object
Existing problems : It may cause a waste of resources and space
/** * @Description: The hungrier singleton * @Author: Boo, boo, boo, boo ~~~ * @Date:2022/6/29 */
public class Hungry {
/** * Suppose this class opens up a large array when it is created * * The problem with this starving singleton mode is that it may cause a waste of resource space * For example, this class will create many large arrays , So the singleton pattern is to instantiate the object * If this object is not used later, a lot of space will be wasted * Therefore, according to the problems of the hungry type, the lazy type singleton mode is introduced */
private byte[] data1 = new byte[1024 * 1024];
private byte[] data2 = new byte[1024 * 1024];
private byte[] data3 = new byte[1024 * 1024];
private byte[] data4 = new byte[1024 * 1024];
/** * A private constructor */
private Hungry() {
}
/** * Hungry han singleton , No matter three, seven, twenty-one , Load the object first */
private final static Hungry HUNGRY = new Hungry();
public static Hungry getInstance() {
return HUNGRY;
}
}
2. An example of lazy style
//--------------------- Base version singleton mode , There are thread safety issues ----------------------
public class LazyMan {
/** * Private structure */
private LazyMan() {
}
/** * Don't instantiate the object first */
private static LazyMan lazyMan;
/** * Check whether the following objects are empty , When it is empty, it is created * @return */
public static LazyMan getInstance() {
if (lazyMan == null) {
lazyMan = new LazyMan();
}
return lazyMan;
}
}
//----------------------- Dual detection lock mode version -----------------------------
public class LazyMan {
/** * Private structure */
private LazyMan() {
}
/** * The double detection lock object is given as volatile To embellish , Prevent command rearrangement , because : * lazyMan = new LazyMan(); This new The operation of objects is not atomic at the bottom * 1. Allocate memory space * 2. Execute construction , Initialize object * 3. Point this object to this space * Suppose now A The thread executes the code that creates the instance , Instruction rearrangement occurs at the bottom The order of three steps to create an object is 1 3 2 * It means threads A The object points to the space before it is initialized , Suppose there is a thread B So far * Threads B In judging the first lazyMan==null When it comes to false, Because the thread A Has pointed to memory space * So at this point, the thread B This object is returned directly , But actually threads A This object has not been initialized yet , So the object returned is nihilistic * So in order to rearrange instructions when creating objects , Add one more volatile Keyword modification */
private volatile static LazyMan lazyMan;
/** * Check whether the following objects are empty , When it is empty, it is created * @return */
public static LazyMan getInstance() {
// This is the first one lazyMan == null The function of is to improve efficiency , Without this layer , Get the lock every time , Getting a lock is actually a very efficient operation
if (lazyMan == null) {
synchronized (LazyMan.class) {
if (lazyMan == null) {
lazyMan = new LazyMan();
}
}
}
return lazyMan;
}
}
3. Static inner class gets the singleton
public class Holder {
/** * Constructor private */
private Holder() {
}
public static Holder getInstance() {
return InnerClass.HOLDER;
}
/** * Create instances of static inner classes */
public static class InnerClass{
private static final Holder HOLDER = new Holder();
}
}
4. Reflection breaking singleton mode
Normal acquisition
public static void main(String[] args) {
LazyMan instance1 = LazyMan.getInstance();
LazyMan instance2 = LazyMan.getInstance();
System.out.println(instance1.hashCode());
System.out.println(instance2.hashCode());
}

Broken ring one : A single instance is obtained in the normal way , A single instance is obtained by reflection
public static void main(String[] args) throws Exception {
LazyMan instance1 = LazyMan.getInstance();
// Get constructor of singleton class
Constructor<LazyMan> declaredConstructor = LazyMan.class.getDeclaredConstructor(null);
// Ignore private constructors
declaredConstructor.setAccessible(true);
// Get instances through reflection
LazyMan instance2 = declaredConstructor.newInstance();
System.out.println(instance1.hashCode());
System.out.println(instance2.hashCode());
}
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-rdP5yLgq-1656521562320)(C:/Users/zhengbo/%E6%88%91%E7%9A%84%E5%AD%A6%E4%B9%A0/Typora%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/image-20220630000533306.png)]](/img/9a/8f7c062ecdd162353fb1ade4097d83.png)
- resolvent , Improve private constructors , The way of triple detection lock , Let's judge from the construction method of the singleton class ,instance1 Is it empty , If it is not empty, an exception is thrown
/** * Private structure */
private LazyMan() {
synchronized (LazyMan.class) {
if (lazyMan != null) {
// The constructor is also called if it is not empty , It means that it is destroyed by reflection , Throw an exception to prevent
throw new RuntimeException(" Do not attempt to use the reflection breaking singleton mode !!!");
}
}
}
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-Qr4TjQgv-1656521562321)(C:/Users/zhengbo/%E6%88%91%E7%9A%84%E5%AD%A6%E4%B9%A0/Typora%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/image-20220630001048394.png)]](/img/38/6a771ca2386608c1066c9edab0feb4.png)
Broken ring II , Create objects without using the references provided in the class , Every time you create an object, you use the reflection method
public static void main(String[] args) throws Exception {
// Get constructor of singleton class
Constructor<LazyMan> declaredConstructor = LazyMan.class.getDeclaredConstructor(null);
// Ignore private constructors
declaredConstructor.setAccessible(true);
// Get instances through reflection
LazyMan instance1 = declaredConstructor.newInstance();
LazyMan instance2 = declaredConstructor.newInstance();
System.out.println(instance1.hashCode());
System.out.println(instance2.hashCode());
}
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-zRs6OtZs-1656521562322)(C:/Users/zhengbo/%E6%88%91%E7%9A%84%E5%AD%A6%E4%B9%A0/Typora%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/image-20220630002101367.png)]](/img/3a/34a9a8223165853929feac48649619.png)
- The solution to this situation , It can be solved by making a mark
/** * Traffic light strategy , Prevent single case cup damage */
private static boolean target = false;
/** * Private structure */
private LazyMan() {
if (!target) {
target = true;
} else {
throw new RuntimeException(" Don't try to break the loop by reflection ");
}
}

Broken ring three , By breaking the fields in the class , Destroy the traffic light strategy
public static void main(String[] args) throws Exception {
// Get constructor of singleton class
Constructor<LazyMan> declaredConstructor = LazyMan.class.getDeclaredConstructor(null);
// Ignore private constructors
declaredConstructor.setAccessible(true);
// Get... In the singleton class target Field
Field target = LazyMan.class.getDeclaredField("target");
target.setAccessible(true);
// Get instances through reflection
LazyMan instance1 = declaredConstructor.newInstance();
// After execution , We change the value of the field to false
target.set(instance1,false);
LazyMan instance2 = declaredConstructor.newInstance();
System.out.println(instance1.hashCode());
System.out.println(instance2.hashCode());
}

The law is strong !!!
5. The way to enumerate , Prevent single cases from being destroyed
/** * @Description: Enumeration prevents the singleton from being destroyed * enum It's also a class * @Author: Boo, boo, boo, boo ~~~ * @Date:2022/6/30 */
public enum EnumSingle {
INSTANCE;
public EnumSingle getInstance() {
return INSTANCE;
}
}
class Test {
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
EnumSingle instance1 = EnumSingle.INSTANCE;
Constructor<EnumSingle> declaredConstructor = EnumSingle.class.getDeclaredConstructor(null);
declaredConstructor.setAccessible(true);
EnumSingle instance2 = declaredConstructor.newInstance();
System.out.println(instance1);
System.out.println(instance2);
}
}
- The final decompiled enumeration type is a parameterized constructor
- Reflection violation enumeration throws an exception

边栏推荐
- How to do a good job in software system demand research? Seven weapons make it easy for you to do it
- Tensorflow2 深度学习十必知
- MySQL advanced - basic index and seven joins
- Tensorflow2 深度学习十必知
- ForkJoinPool
- Tsinghua only ranks third? 2022 release of AI major ranking of Chinese Universities of soft science
- Advanced embedded application of uni app [day14]
- [Collection - industry solutions] how to build a high-performance data acceleration and data editing platform
- Type ~ storage ~ variable in C #
- 煤炭行业数智化供应商管理系统解决方案:数据驱动,供应商智慧平台助力企业降本增效
猜你喜欢

Geoffrey Hinton: my 50 years of in-depth study and Research on mental skills

教你30分钟快速搭建直播间

【TiDB】TiCDC canal_json的实际应用

How to solve the lock-in read-only alarm of AutoCAD Chinese language?

C# Winform程序界面优化实例

领导:谁再用 Redis 过期监听实现关闭订单,立马滚蛋!

iCloud照片无法上传或同步怎么办?

Classic problem of leetcode dynamic programming (I)

Sword finger offer 17 Print from 1 to maximum n digits

Hospital online consultation applet source code Internet hospital source code smart hospital source code
随机推荐
Glacier teacher's book
The company was jailed for nonstandard bug during the test ~ [cartoon version]
详解单例模式
MySQL advanced - Architecture
MRO工业品采购管理系统:赋能MRO企业采购各节点,构建数字化采购新体系
Digital intelligent supplier management system solution for coal industry: data driven, supplier intelligent platform helps enterprises reduce costs and increase efficiency
充值满赠,IM+RTC+X 全通信服务「回馈季」开启
Vulnerability recurrence ----37. Apache unomi Remote Code Execution Vulnerability (cve-2020-13942)
Vulnerability recurrence ----- 35. Uwsgi PHP directory traversal vulnerability (cve-2018-7490)
挑选智能音箱时,首选“智能”还是“音质”?这篇文章给你答案
100 examples of bug records of unity development (the first example) -- shader failure or bug after packaging
Redis - persistent RDB and persistent AOF
MySQL advanced - basic index and seven joins
Flink series: checkpoint tuning
How to do a good job in software system demand research? Seven weapons make it easy for you to do it
又一篇CVPR 2022论文被指抄袭,平安保险研究者控诉IBM苏黎世团队
Leader: who can use redis expired monitoring to close orders and get out of here!
Flink系列:checkpoint调优
如何做好软件系统的需求调研,七种武器让你轻松搞定
AI chief architect 10-aica-lanxiang, propeller frame design and core technology