Singleton design pattern and dynamic agent design pattern

solved problem

There should only be one object in one application scope and one class.

Features of the single-column design pattern

1. Construct a private (new object cannot be made by normal means—because it can be called in a private method through reflection)
2. Static member variables (store a reference to a single-column object)
3. Provide a public static access method to obtain a single-column object

Two ways

Lazy man style: there will be thread safety issues (this is the most frequently asked interview)
Hungry man style: there is no thread safety issue

The difference between hungry man and lazy man

Hungry Chinese style is to create the object regardless of whether you use it or not.
——It will be a waste of resources.
-When creating an object, there will be no multithreading.
Insert picture description here
Lazy man style, it will only be created the first time you visit.
——Also called lazy loading, because when it is loaded, there will be multi-threaded access, plus there are member variables in the accessed class.
Insert picture description here
Insert picture description here
Insert picture description here
Insert picture description here

Common normative writing in singleton mode

1. Double check lock (DCL) + volatile
2. Static inner class

When is the single-column object of the hungry man mode created?
When the class corresponding to the singleton object is initialized, the singleton object will be created! !
What are the timings of class initialization? Through new Student, through access to static member variables. .

When the JVM loads a class, the JVM locks the thread that loads the class, that is to say, it is thread-safe when the class is loaded. There will be no thread safety issues.

How to judge thread safety issues?
1: Whether there is multi-threading is
2: Whether there is shared data is
3: Whether there is a non-atomic operation (for bytecode instructions)

Atomic understanding

new Student(); i++;
Is it an atomic operation? no

How to ensure atomicity? Lock

The first role of volatile: you can disable the cpu cache or working memory

Visibility understanding:
Insert picture description here
orderly understanding:
int x; boolean a;
x = 20; step3 a = false; step4
There is no dependency between x and a (whether there is a happend-before relationship),
so JVM will consider For performance issues, it is possible to reorder instructions in step3 and step4.

int x = 10; int y ;
y = x+10;

Guess you like

Origin blog.csdn.net/yang13676084606/article/details/107418733