Live and Let Die ☠️ Life and Death of Java Objects
Understanding the life cycle of objects is crucial for developers. Knowing when objects are created, used, and destroyed helps manage memory efficiently and write robust applications. It is also critical for understanding exception handling and threads.
When the JVM starts up, it claims some memory from the operating system, which can run out if we don’t write good code.
The memory region that stores temporary variables created by each method is the stack. It follows the Last In, First Out (LIFO) principle. The currently running method is always the one on top of the stack.
When a function is added, a new block of memory, called a stack frame, is created on top of the stack for the function's local variables and some bookkeeping information.
Scope and Lifetime: The variables in the stack exist only while the function is executing. Once the function ends (reaches its final curly brace), its stack frame is removed, and the variables are destroyed.
While objects live on the garbage-collectible heap, local variables live on the stack.
The Heap: This is where objects (created with the new keyword) dwell. It is a region of memory for dynamic allocation. Unlike the stack, the heap does not follow a strict allocation order, and access to heap memory is slower.
Garbage Collection: This is an automatic process that reclaims memory by deleting objects that are no longer accessible.
Instance Variable: This is a variable declared inside a class, not inside a method. Instance variables live on the heap with their owner objects.
What if the local variable is an object? A non-primitive variable holds only a reference to an object. This reference goes on the stack.
An object lives as long as there are live references to it. Once an object runs out of live references, it becomes eligible for garbage collection. We can get rid of an object’s reference:
· When it goes out of scope.
· When the reference is assigned to another object.
· When you manually set it to null.
Well, that was a little weird; the subject of death is always a bit hard to talk about. However, understanding the lifecycle of Java objects, from their creation to their eventual removal, is essential for writing efficient and effective code. By managing memory wisely and leveraging garbage collection, you can ensure that your applications run smoothly and avoid common pitfalls such as memory leaks.
For more on this subject:
Head first Java, 3rd Edition.
https://docs.oracle.com/cd/E13150_01/jrockit_jvm/jrockit/geninfo/diagnos/garbage_collect.html
https://www.freecodecamp.org/news/garbage-collection-in-java-what-is-gc-and-how-it-works-in-the-jvm/