当前位置:网站首页>About some details of final, I have something to say - learn about final CSDN creation clock out from the memory model
About some details of final, I have something to say - learn about final CSDN creation clock out from the memory model
2022-07-07 07:29:00 【I like canned fish best】
Thousands of people , Thanks for the second you see this . I hope my article can help you !
May you in the days to come , Keep loving , Go to the mountains and seas !!
. : About
final
keyword , It is also a keyword we often use , Can be decorated on a class 、 Or modify it in a variable 、 On the way , In this view, some of the immutability that defines it !Like we often use String Class , It is
final
To modify the class , And its character array is alsofinal
The modified . But somefinal
Have you really understood some details of ?Start with this article , Take you to know more about
final
The details of the !
Learn from the memory model final
on top , We know about... In the case of a single thread final
, But for multithreading concurrency final
, Do you understand ? Multithreading concurrency , We must also know the concept of a memory model :JMM
.
JMM
JMM It defines the abstract relationship between thread and main memory : Shared variables between threads exist in main memory (MainMemory) in , Each thread has a private local memory (LocalMemory) That is, share a copy of the variable , The thread is stored in local memory to read 、 Write a copy of the shared variable . Local memory is Java An abstraction of the memory model , It doesn't really exist . It covers caching 、 Write buffer 、 Register, etc .
And in this memory model , When a computer is executing a program , To improve performance , Compilers and processors often reorder instructions . So here comes the question , What is reordering ?
Reorder
In fact, for our program , Can be divided into different instructions , Each instruction contains multiple steps , Each step may use different hardware . We can split each instruction into five stages :
Think of it like this, if it's sequential execution of instructions , That may be relatively slow , Because you need to wait for the last instruction to complete , To wait for the next step :
And if instruction reordering happens , In fact, it can't shorten the execution time of a single instruction , But it improves instruction throughput in disguise , You can run different stages of five instructions simultaneously in one clock cycle .
Let's analyze the execution of the code , And think about it :
a = b + c;
d = e - f ;
In the original way , Will load first b and c, Proceed again b+c Operation assignment to a, And then it loads e and f, Finally, it's going on e-f Operation assignment to d.
There is no room for optimization ? We're executing b+c Operation assignment to a when , You may have to wait b and c End of load , Then we can do another sum operation , So there may be a pause waiting time , In turn, the following code may also have pause waiting time , This reduces the execution efficiency of the computer .
To reduce the pause waiting time , We can load it first e and f, Then go again. b+c Operation assignment to a, It's good for the program ( Serial ) It doesn't matter , But it reduces the pause and wait time . since b+c Operation assignment to a Need to pause and wait , It's better to do something meaningful .
summary : Command rearrangement for improvement CPU Processing performance is essential . But it will cause some instructions to be out of order . So our final
What does it do for instruction reordering ? Now let's take a look !
final Domain reordering rules
about JMM For the memory model , It's right final
Fields have the following two reordering rules :
Write : In the constructor
final
Domain write , Then assign the reference of the constructor to a reference variable , Operations cannot be reordered .read : Read an include for the first time
final
The reference of the object of the field and the subsequent initial writing of thisfinal
Domain , Cannot reorder .
Let's explain the details according to the code demonstration :
Code :
package com.ygt.test;
/** * test JMM The memory model is right final Rules for field reordering */
public class JMMFinalTest {
// Common variables
private int variable;
// final Variable
private final int variable2;
private static JMMFinalTest jmmFinalTest;
// In the construction method , Combine ordinary variables with final Variable to write
public JMMFinalTest(){
variable = 1; // 1. Write ordinary variables
variable2 = 2; // 2. Write final Variable
}
// Imitate a write operation --> Assuming that thread A To write
public static void write() {
// new Current class object --> And complete the assignment operation in the constructor
jmmFinalTest = new JMMFinalTest();
}
// Imitate a read operation --> Assuming that thread B Perform read operation
public static void read() {
// Read operations :
JMMFinalTest test = jmmFinalTest; // 3. Read the reference of the object
int localVariable = test.variable;
int localVariable2 = test.variable2;
}
}
Write final Domain reordering rules
Write final
The field reorder is performed on... Within the constructor final
Domain write , Then assign the reference of the constructor to a reference variable , Operations cannot be reordered . On behalf of... Is prohibited final
The initialization of the field must be in the constructor , Can't reorder outside the constructor , The implementation of this rule mainly includes two aspects :
- JMM The memory model prohibits the compiler from
final
Write - reorder of fields outside the constructor ; - The compiler will be there
final
Field write and constructor return Before returning , Insert astorestore
Memory barrier . This memory barrier prevents the processor from turningfinal
Write - reorder of fields outside the constructor .
Let's analyze write Method , Although there is only one line of code , But he actually has three steps :
- stay JVM Apply for a piece of memory space in the heap
- Object to initialize
- Assign the reference address of the memory space in the heap to a reference variable jmmFinalTest.
For ordinary variables variable Come on , Its initialization operations can be reordered outside the constructor , That is, our steps are not original 1-2-3 Do you , Now it may cause 1-3-2 In this way, the initialization operation is completed after the constructor returns !
And for final
Variable variable2 Come on , Its initialization must be within the constructor , namely 1-2-3.
Let's look at a possible picture :
For the visibility of variables , Because ordinary variables variable A phenomenon of reordering may occur , The values read may be different , May be 0 Or is it 1. however final
Variable variable2, The value it reads must be 2 了 , Because there is a StoreStore
Memory barrier to ensure reordering with the following operations .
thus it can be seen , Write final
The reordering rule of the domain can even ensure that we Before the object reference is visible to any thread , Object's final The domain has been properly initialized , The common domain does not have this guarantee .
read final Domain reordering rules
Read an include for the first time final
The reference of the object of the field and the subsequent initial writing of this final
Domain , Cannot reorder . How to achieve it ?
It's actually the processor reading final
Insert one before the field operation LoadLoad
Memory barrier .
Let's analyze read Method , He really has three steps :
- First read reference variables jmmFinalTest;
- First read reference variables jmmFinalTest Common domain variables variable;
- First read reference variables jmmFinalTest Of
final
Domain variables variable2;
We sort normally with write operations , For reading situations, it may happen :
For the common domain variable of the read object variable Reordering may occur , Reordered to the front of the read object reference , The thread... Appears B Before reading the object reference, you are reading the common domain variable of the object , This is obviously the wrong operation .
And for final
The read operation of the domain passes LoadLoad
The memory barrier ensures that when reading final
The reference of this object has been read before the domain variable , Thus, the above situation can be avoided .
thus it can be seen , read final
The reordering rules of the domain can ensure that we Reading about an object final Before domain , Be sure to read this first, including this final A reference to an object of a domain , The common domain does not have this guarantee .
final Object is a reference type
I already know above final
The domain object is a reordering rule of the basic data type , But what if the object is a reference type ? Let's go on :
When final
The domain object is a reference type , Write final
Reordering rules for fields The following constraints are added :
I have one in the constructor final
Writes to a member field of a referenced object , And then assign a reference to the constructed object outside the constructor to the reference variable . It still sounds a little hard to understand, doesn't it , Don't worry , Look at the code !
Be careful. : Previous writing final
There are the same sorting rules as fields , Only a rule is added for reference type objects .
Code :
package com.ygt.test;
/** * test final Reading and writing when referencing type objects */
public class ReferenceFinalTest {
// Define reference objects
final Person person;
private ReferenceFinalTest referenceFinalTest;
// Initializes in the constructor , And perform assignment operation
public ReferenceFinalTest(){
person = new Person(); // 1. initialization
person.setName(" James !"); // 2. assignment
}
// Threads A Come in and write , The implementation will referenceFinalTest initialization
public void write(){
referenceFinalTest = new ReferenceFinalTest(); // 3. Initialize constructor
}
// Threads B Come in and write , Realization person Reassign operation .
public void write2(){
person.setName(" Davis "); // 4. Reassign operation
}
// Threads C Come in and read , Read the current person Value
public void read(){
if(referenceFinalTest != null) {
// 5. Read reference object
String name = person.getName(); // 6. Read person The value of the object
}
}
}
class Person{
private String name;
private int age;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
First , Let's draw a diagram of what might happen :
The execution order of our threads :A ——> B ——> C
Then we explain the read-write operation methods in detail :
Write final Domain reordering rules
We know from before , We final
The write of the field prohibits reordering outside the constructor , therefore 1 and 3 Reordering is not allowed .
And for our new constraints , I have one in the constructor final
Writes to a member field of a referenced object , And then assign a reference to the constructed object outside the constructor to the reference variable . namely final
The member attribute of the reference object of the domain is written to setName(" James ")
It is not possible to assign the constructed object to the reference variable later jmmFinalTest Reorder , therefore 2 and 3 Cannot reorder .
So our step is 1-2-3.
read final Domain reordering rules
For multithreading ,JMM The memory model at least ensures that threads C Reading object person Member properties of , First read the reference object person 了 , You can read the thread A Yes final
Domain reference object person Write of member properties of .
Maybe this time the thread B about person The writing of the member property of is temporarily invisible , No thread is guaranteed B Write to thread C The visibility of , Because maybe threads B With threads C There is a contention problem of thread preemption , The results may be different !
Of course , If you want to save the visible , We can use Volatile Or synchronous lock .
🥩 Summary
We can classify according to the data type :
Basic data type :
- Write : In the constructor
final
Domain write , Then assign the reference of the constructor to a reference variable , Operations cannot be reordered . That is to prohibitfinal
Field writes are reordered outside the constructor . - read : Read an include for the first time
final
The reference of the object of the field and the subsequent initial writing of thisfinal
Domain , Cannot reorder .
Reference data type :
Add additional constraints on basic data types :
Do not use a constructor on One final Writes the member domain properties of the decorated object And then The reference of the constructed object is assigned to the reference variable Reorder .
summary
I believe you are right final This keyword has a certain understanding , In fact, it is necessary to expand your knowledge , Or when others ask you , You'll be speechless , And once you analyze your knowledge every day , You'll talk a lot in your future dialogues , Shining !!! Right , We still have a handful of things waiting for us to explore and explore ! The next step is to concentrate on learning for a period of time , Not blundering , Don't be discouraged !
Let's cheer together ! I am not talented , If there is anything missing 、 The wrong place , Welcome all talent leaders Comment on Criticism and correction in ! Of course, if this article is sure to help you a little , Please kindly and lovely talent leaders give me a give the thumbs-up 、 Collection Let's go , One key, three links , Thank you very much !
Learn here , The world is closed today , Good night, ! Although this article is over , But I'm still , It's never over . I will try to keep writing . The coming days would be long , Don't be afraid of the slow horse !
Thank you for seeing this ! May you live up to your age , No regrets for youth !
边栏推荐
- Outsourcing for four years, abandoned
- How do I get the last part of a string- How to get the last part of a string?
- Chinese and English instructions prosci LAG-3 recombinant protein
- Outlier detection technology of time series data
- 95后CV工程师晒出工资单,狠补了这个,真香...
- transform-origin属性详解
- A concurrent rule verification implementation
- 【云原生】内存数据库如何发挥内存优势
- Advanced practice of C language (high level) pointer
- MySQL service is missing from computer service
猜你喜欢
Detailed explanation of neo4j installation process
How does an enterprise manage data? Share the experience summary of four aspects of data governance
虚拟机的作用
Fast quantitative, abbkine protein quantitative kit BCA method is coming!
Freeswitch dials extension number source code tracking
Pass parent component to child component: props
Pass child component to parent component
1、 Go knowledge check and remedy + practical course notes youth training camp notes
07_ Handout on the essence and practical skills of text measurement and geometric transformation
三、高质量编程与性能调优实战 青训营笔记
随机推荐
Detailed explanation of transform origin attribute
Summary of customer value model (RFM) technology for data analysis
MIPS uclibc cross compile ffmpeg, support g711a encoding and decoding
Wechat applet full stack development practice Chapter 3 Introduction and use of APIs commonly used in wechat applet development -- 3.10 tabbar component (I) how to open and use the default tabbar comp
抽丝剥茧C语言(高阶)指针进阶练习
关于二进制无法精确表示小数
FullGC问题分析及解决办法总结
URP - shaders and materials - simple lit
Dynamics CRM server deployment - restore database prompt: the database is in use
父组件传递给子组件:Props
Role of virtual machine
Chinese and English instructions prosci LAG-3 recombinant protein
js小练习----分时提醒问候、表单密码显示隐藏效果、文本框焦点事件、关闭广告
选择商品属性弹框从底部弹出动画效果
【leetcode】1020. Number of enclaves
Advanced practice of C language (high level) pointer
考研失败,卷不进大厂,感觉没戏了
Software acceptance test
PostgreSQL source code (59) analysis of transaction ID allocation and overflow judgment methods
Databinding exception of kotlin