Sunday, 22 December 2019

JVM Memory Management

Escaping Reference

Java passing variable to a method by a copy of variable or a copy of the reference that points to the object located in the heap. If exposing a reference, meaning that the instance may be musted unexpectedly. thus we need to escape reference.

Garbage
Stack: reference; (stack overflow exception)
Heap: instance   (running out memory exception)

when an instance in heap has no reference pointing to it, then this instance is eligible garbage.

Analysing Tool
Goto JDK bin folder, find the application 'jvisualvm' and run it.
It is a visualizing tool to show heap memory (used and unused).

The curve used heap memory may indicate the trend of memory leak.

Garbage Collection Process

java may automatically free memory as objects are not used any more.
it is called 'mark and sweep', consisting of two processes; 1) marking instances that need to be retained and 2) then sweeping those that no needed any more.

Before implementing this process, all threads need to be stopped. (this is the downside of GC)
After that, Checking the references on the stack; marking the instance it is pointing to, and the instances it depends on.

Heap Generations

For solving GC freezing(all threads need to be stopped as carrying out GC.)
Heap memory is classified into the young generation and the old generation.
If an object survives from a GC, then its life cycle may last until the end of the application.

the new object is created in the young generation space. (minor collection)
the surviving object is copied into the olde generation space. (major collection)

PermGen and MetaData

Java 6
Heap memory:
the young generation, old generation, and permanent generation(string and class metadata)

Java 7
the string is moved to the old generation.

From Java 8
class metadata is moved to a separate space, called metaspace, which is not part of heap memory any more. meaning that it has no size limitation any more.

Tunning JVM
setting up the max heap size: -Xmx512m;  start heap size: -Xms125m
java doc shows default heap size = 256mb

Before java 8, PermGen has been removed from java 8
Max PermGen Size: -XX=256M

-verbose:gc   print out to console when a GC takes place
-Xmn256m  set young generation size
-XX:HeapDumpOnOutOfMemory creating a heap dump file.

different type of garbage collector
-XX:+UseSerialGC  serial: using a single thread :
-XX:+UseParrelGC  parallel:  using multiple threads
-XX:+UseConcMarkSweepGC
-XX:+UseG1GC
                             


No comments:

Can Jackson Deserialize Java Time ZonedDateTime

Yes, but must include JSR310. Thus ZonedDateTime can be deserialized directly from JSON response to POJO field. <dependency> <g...