What is the STW?

STW(Stop-the-world) literally means to stop the world

When the garbage collector searches for the corresponding useful object through GCRoots, if other worker threads are not stopped, the object reference may change during the search process or the GCRoots itself may change, resulting in inaccurate or incorrect data finally located. All garbage collectors currently produce STW

For example, the CMS concurrent garbage collector and the CURRENT G1 garbage collector, the default in the JDK, generate STW when GCRoots are marked in the first step and the Final Mark

Safe Point

STW is a concept, but how exactly does it work to suspend a worker thread? The JVM sets safety points when executing our code, adding safety points around loops, method calls, exception fires, and so on

For example, when we drive through a traffic light, we will check whether it is green and go ahead. If it is red, we will wait until it changes to green and go ahead

Similarly, the SAFE point for the JVM is to set the safe point at each “intersection”. When the program executes at the corresponding intersection, check to see if GC is currently needed, and if GC is needed, wait in place

If there are too many safety points, obviously, if we drive with too many traffic lights every one meter and two meters, then our efficiency will be greatly reduced. On the contrary, if there are too few traffic lights, then it may be more difficult for pedestrians to cross the street (this is just a metaphor).

When there are too many safe points in the process of program execution, resources will be consumed. Every time we reach the safe point, we have to check whether GC needs to run. If there are too few safe points, the GC thread will wait for a long time and the GC efficiency will be low

Safe Region

Safe zones? Why do we need safe zones when we have safe zones?

Because some of our threads may execute in several states, including BLOCK and TIME_WAIT or WAIT, it may take a long time to WAIT for the thread to reach a safe point in these states

So a security zone is designed, and a security zone means that there will be no object reference changes in a particular piece of code

For example, the thread does not execute at all when it is asleep, just as we are driving into the service area on the highway to rest. In this area, the GC thread does not need to wait for the application thread to run to a safe point to query