|
Java manages memory. Therefore, the programmer
does not need to allocate memory at the time of
object creation. In addition, programmer does not
need to free the memory explicitly.
|
|
Object
creation
Object is constructed either on a memory heap or
on a stack.
-
Memory heap
Generally the objects are created using the
new
keyword. Some heap memory is allocated to
this newly created object. This memory
remains allocated throughout the life cycle
of the object. When the object is no more
referred, the memory allocated to the object
is eligible to be back on the heap. The
process of releasing such memory back is
called as garbage collection.
-
Stack
During method calls, objects are created for
method arguments and method variables. These
objects are created on stack.
Such objects are eligible for
garbage-collection when they go out of scope.
More in ebook
|
|
Garbage
Collection
- Garbage Collection is a low-priority thread
in java.
- Garbage Collection cannot be forced
explicitly. JVM may do garbage collection if it
is running short of memory.
The call System.gc() does NOT force the
garbage collection but only suggests that the
JVM may make an effort to do garbage
collection.
- Garbage Collection is hardwired in Java
runtime system. Java runtime system keeps the
track of memory allocated. Therefore, it is
able to determine if memory is still usable by
any live thread. If not, then garbage
collection thread will eventually release the
memory back to the heap.
- Garbage Collection usually adopts an
algorithm, which gives a fair balance between
responsiveness (how quickly garbage-collection
thread yields?) and speed of memory recovery
(important for memory-intensive operations).
Responsiveness is especially important in real
time systems.
More in ebook
|
|
How an
object becomes eligible for Garbage
Collection
More in ebook
|
|
Though java does most of the memory management
work, programmers cannot be sure about memory
leaks. One can still have memory leaks despite
garbage-collection. This can be due to poor
programming such as orphaning (making all
references to null) too many objects. In a rare
case, such program may run out of memory.
|