2020-10-24 Essay: What is CAS, Object object = new Object(); How to layout objects created in this way in system memory

To prepare for the interview, I recently reviewed CAS, principles and ABA issues.

What is CAS

CAS simply means comparison and exchange. It
is a user mode operation (the operating system can be divided into user mode and kernel mode.)
Cpu supports cas. Generally, current cpus are multi-core.
The withdrawal of cas in java: the unsafe method in Java calls the underlying C++ implementation. The unsafe method in c++, c++ can call the bottom layer of the operating system. Explain that cas is to not disturb the heavyweight lock of the operating system, which is the lock bus. To implement the lock mechanism. The cpu reads the value from the memory and then performs calculations and then writes it back to the memory. The method at this time is to judge whether the value read is the same as the current one, which is the so-called comparison. If the same, modify the value in the memory to the value calculated by the cpu. ABA is that the value in this memory may have changed but changed back to the original value. At this time, you need to add a version number to judge. Don't know how to explain it, do you understand?
AbA problem is solved with version number

Object layout
1. Mark word three functions Record lock information, record gc information, record hashcode, which is identify hashcode
2. Record object information, object pointer
3. Record member variables
4. Object alignment, bytecode must be divisible by 8 Efficient

The process of lock upgrade: the following is my dull understanding

Preference lock, because in most cases the lock will only be occupied by one thread, so there is little competition. There is no lock competition, so the post is biased to lock. The process of posting is cas operation. The first thread holds the bias lock, and the pointer of the first thread is pasted to the bias lock. 90% of the time is one thread. It is a waste of time and resources to design a competing lock.
00 01 10 11 status These are the lock flags in the markword, which can be printed to the console with jcl. There are two types of 01 flags, 001 and 101. 001 is a non-locked state, and 101 is a biased lock. 00 is lock-free, or lightweight lock (spin locks
. There are many rules for biased locks.
If there are threads competing, they will be upgraded to lightweight locks, or spin locks. Some also care about this lock-free. The lock-free is not applying for a heavyweight lock with the operating system.

Guess you like

Origin blog.csdn.net/AntdonYu/article/details/109262288