One of the main advantages of using Java is that you don't have to worry about discarding objects, that is, let Java runtime be responsible for memory management of Java objects.
This is accomplished by having the Java runtime do garbage collection of Java objects that are no longer in use.
Garbage collection is a more complex process. Typically, the Java runtime traverses the heap, checking for objects that are no longer referenced by other objects, so that they can be safely deleted, however, because garbage collection consumes CPU cycles, it may affect the execution of application code. That is, if garbage collection is performed during the execution of application code, the response time of the application code may be prolonged. This can result in an extension of user transaction latency. Worse, because the user does not know when garbage collection is to be made, the delay extension is unpredictable.
Live applications have strict time requirements, that is, they must execute application code under certain, known latency conditions. Therefore, the unpredictable delay extension caused by garbage collection becomes a problem.
So what is the solution to this problem? An obvious solution is to not use Java for real-time applications. This is a next election. As a programming language and a development platform, Java has many advantages. We should be able to solve this problem in Java.
Another solution is to use another memory management method in Java instead of a garbage collector. RTSJ (Real-time specification for Java) defines the concepts of immortal memory and scoped memory. Immortal Memory (Immortal memory) is memory that is never garbage collected, as long as the JVM exists. Scope memory (Scoped memory) is the memory allocated and freed by block. That is, the user explicitly creates an area of memory to hold the object, and the objects in that zone are freed when the zone is destroyed. No garbage collection is required, whether it is immortal or scope memory. However, there is also a drawback: the burden of managing memory falls on the user, just as C + + applications do. The price is still high. Is there a better way?
Let's reconsider the garbage collection. The main problem with garbage collection is the unpredictable latency spikes it causes. Can this unpredictable behavior be avoided? or can you limit (that is, constrain) this unpredictable behavior? By performing garbage collection more frequently, we can limit the maximum latency time. This is the method used by WLRT. As a result, garbage collection becomes a predictable task with known costs, allowing real-time developers to think and model as needed. And, more importantly, we don't sacrifice Java for ease of use.
Note: It should be noted that while there are garbage collection and other memory management techniques, Java programs may still have memory leaks. For example, when a Component object is not needed, it is not removed from the container.