SlideShare una empresa de Scribd logo
1 de 9
Java Session 10
How Garbage collection works?
• Java manages memory automatically
• The Garbage collector is part of the Java virtual machine
• Objects referenced by java variables are created in heap memory
• As long as any variable references an object, it is retained.
• When all references expire, the object is eligible to be garbage collected.
• We can explicitly expire persistent objects by setting it to null
• Variables local to function or code block expire when function is complete.
• How Garbage collection works :
 The garbage collector runs on its own thread. Mark and sweep approach
 When garbage collector identifies a de-referenced object, it can destroy it and reclaim memory
 You as the programmer cannot force garbage collection
 Methods System.gc() and Runtim.gc() can request garbage collection, but there is no guarantee it will happen
 If no memory is available for newly requested object, JVM throws OutOfMemoryError.
• Tips for managing memory : Use command line options to manage amount of available heap memory
• java –Xms256m HelloWorld initial heap size
• Java –Xmx256m HelloWorld Maximum heap size
• Java –Xmn256m HelloWorld Heap size for young generation objects.
How Garbage collection works?
Java (JVM) Memory Types
• Heap Memory : Heap memory is also called as shared memory. As this is the place where multiple threads will
share the same data. The heap will be created at JVM startup and the size can be static or dynamic. The JVM
specification mandates a Garbage Collection mechanism for reclaiming the memory of an object on the Java heap. The
implementation of the Garbage Collector is not specified, but it is not allowed to provide the programmer with an
explicit mechanism for deallocating the memory of an object.
• Non-heap Memory : It comprises of ‘Method Area’ and other memory required for internal processing. So here the
major player is ‘Method Area’.
• Method Area : The method area is responsible for storing class information. The Class-Loader will load the
bytecode of a class and will pass it to the JVM. The JVM will generate an internal class representation of the
bytecode and store it in the method area. The internal representation of a class will have the following data
areas:
i. Runtime Constant Pool Numeric constants of the class of types int, long, float or double, String-constants and
symbolic references to all methods, attributes and types of this class.
ii. Method CodeThe implementation (code) of all methods of this class including constructors etc.
iii. Attributes A list of all named attributes of this class.
iv. FieldsValues of all fields of this class as references to the Runtime Constant Pool.
• Memory Pool : Memory pools are created by JVM memory managers during runtime. Memory pool may
belong to either heap or non-heap memory.
• Runtime Constant Pool : A run time constant pool is a per-class or per-interface run time representation of the
constant_pool table in a class file. Each runtime constant pool is allocated from the Java virtual machine’s method
area.
• Java Stacks or Frames : Java stacks are created private to a thread. Every thread will have a program counter (PC)
and a java stack. PC will use the java stack to store the intermediate values, dynamic linking, return values for
methods and dispatch exceptions. This is used in the place of registers.
Memory Generations
• HotSpot VM’s garbage collector uses generational garbage collection. It separates the JVM’s memory into and they are
called young generation and old generation.
• Young Generation : Young generation memory consists of two parts, Eden space and survivor space. Shortlived
objects will be available in Eden space. Every object starts its life from Eden space. When GC happens, if an object is
still alive and it will be moved to survivor space and other dereferenced objects will be removed.
• Old Generation – Tenured and PermGen : Old generation memory has two parts, tenured generation and permanent
generation (PermGen). PermGen is a popular term. We used to error like PermGen space not sufficient. GC moves live
objects from survivor space to tenured generation. The permanent generation contains meta data of the virtual
machine, class and method objects.
• Local Variables are stored in Frames during runtime.
• Static Variables are stored in Method Area.
• Arrays are stored in heap memory.
• Errors :
 Javadoc of java.lang.OutOfMemoryError : Thrown when the Java Virtual Machine cannot allocate an object
because it is out of memory, and no more memory could be made available by the garbage collector.
 In the heap we get an OutOfMemoryError, if the garbage collector cannot reclaim enough memory for a new object.
In such situation the Sun HotSpot JVM shows this error message: Exception in thread "main":
java.lang.OutOfMemoryError: Java heap space
 if the application tries to create an array on the heap that is bigger than the total heap size. error can be : Exception in
thread "main": java.lang.OutOfMemoryError: Requested array size exceeds VM limit
 If there is not enough memory in the method area for creating a new class, the Sun HotSpot implementation gets an
error in the permanent generation:Exception in thread "main": java.lang.OutOfMemoryError: PermGen space
• If there are too many threads in the JVM and there is not enough memory left to create a new thread. I’ve seen below
error because the memory limits of a process have been reached (especially in 32bit operating systems, e.g. on
Windows 32bit it is 2GB) or the maximum number of file handles for the user that executes the java process has been
reached. Exception in thread "main" java.lang.OutOfMemoryError: unable to create new native thread
• Memory allocation error on a native stack (JNI method call) : Exception in thread "main":
java.lang.OutOfMemoryError: <reason> <stacktrace> (Native method)
• It is also interesting that a memory allocation error on the JVM stack (too many frames on the stack) does not throw an
Java OutOfMemory error but as the JVM specification mandates: java.lang.StackOverflowError.
• If there is not enough memory left on the operating system level – which is normally true if other processes are using
all of the available memory or the swap space is configured too small. Error: Exception in thread "main":
java.lang.OutOfMemoryError: request <size> bytes for <reason>. Out of swap space?
Java Memory Leaks
• In Java objects get generated on the heap and live on as long as they are referenced. The garbage
collector checks during it GC-phases if the object is still referenced – and does mark it as “garbage” and
clean it up later when this is no longer the case (the actual behaviour differs for different gc-algorithms,
like the Copying Collectors or Garbage-First, but is not of importance for understanding liveness). But
not every reference is important for surviving, but only so called GC root references. Especially when
understanding Memory Leaks, GC roots are a central concept to identify the important references to an
object. Garbage Collector Roots are special objects which do not have incoming references and are
responsible for keeping referenced objects alive. When an object cannot be reached directly or
indirectly from a GC root, it will be marked as “unreachable” and made eligible for garbage collection.
Simply speaking, there are three kinds of GC roots:
 Temporary variables on the stack of a thread
 Static members of a loaded class
 Special native references from JNI
• Usually there are tree types of issues with Java OutOfMemoryError problems in heap memory:
 Objects, which can be reached via a GC root reference, but are actually no longer used by
application code. Those are called Java Memory Leaks.
 Too many or too large objects. So there is not enough heap available for the application to
execute. Usually happens when there are large objects kept in cache like structures.
 Too many temporary objects. So there is just for a short time not enough memory. Usually
happens in load scenarios where many temporary objects are used.
 Ex: http://ideone.com/1QowAQ
Java Memory Leaks
• Java Memory Leaks occur when objects still have a GC root reference, but are not actually used
anymore. Those “Loitering Objects” stay around for the whole life of the JVM. If the application is
creating those “dead objects” on and on, the memory will be filled up and eventually result in a
java.lang.OutOfMemoryError. Typical causes are static collections, which are used as a kind of cache.
Usually objects are added, but never removed (Let’s face it: How often have you used add() and put()
and how often used remove() methods?). Because the objects are referenced by the static collection,
they cannot be freed up anymore, as the collection has a GC root reference via the classloader.
• Depending on the creation frequency and the object size, as well as the size of the Java heap, the
OutOfMemoryError occurs sooner or later. Especially those “creeping memory leaks” can be found in
many applications, but are usually “ignored” by:
• Using large heaps to delay the error. Happens frequently nowadays, as the old 32bit memory
limit has vanished through the usage of 64 bit JVMs.
• Restarting the application server during the night. This “resets” the memory usage. If the
memory leak takes longer than 24 hours to become severe, this will help.
• But both variants are dangerous, as they have negative impact on the system performance and
are heavily influenced by the system usage. A change in usage or more “traffic” can produce the
error faster than expected. Garbage collection times also have a negative effect on the
application performance, as the increasing “tenured generation” causes longer “Mark”-Phases
during garbage collection, resulting in longer pause times, which can be observed as system
hangs.
• Refer: https://gist.github.com/rajeevprasanna/04b4c9322a5245877c1f
Javasession10

Más contenido relacionado

La actualidad más candente

Fixing the Java Serialization Mess
Fixing the Java Serialization Mess Fixing the Java Serialization Mess
Fixing the Java Serialization Mess
Salesforce Engineering
 
JVM for Dummies - OSCON 2011
JVM for Dummies - OSCON 2011JVM for Dummies - OSCON 2011
JVM for Dummies - OSCON 2011
Charles Nutter
 

La actualidad más candente (20)

Black Hat EU 2010 - Attacking Java Serialized Communication
Black Hat EU 2010 - Attacking Java Serialized CommunicationBlack Hat EU 2010 - Attacking Java Serialized Communication
Black Hat EU 2010 - Attacking Java Serialized Communication
 
Java Deserialization Vulnerabilities - The Forgotten Bug Class
Java Deserialization Vulnerabilities - The Forgotten Bug ClassJava Deserialization Vulnerabilities - The Forgotten Bug Class
Java Deserialization Vulnerabilities - The Forgotten Bug Class
 
Deserialization vulnerabilities
Deserialization vulnerabilitiesDeserialization vulnerabilities
Deserialization vulnerabilities
 
OWASP SD: Deserialize My Shorts: Or How I Learned To Start Worrying and Hate ...
OWASP SD: Deserialize My Shorts: Or How I Learned To Start Worrying and Hate ...OWASP SD: Deserialize My Shorts: Or How I Learned To Start Worrying and Hate ...
OWASP SD: Deserialize My Shorts: Or How I Learned To Start Worrying and Hate ...
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in Practice
 
Java Deserialization Vulnerabilities - The Forgotten Bug Class (RuhrSec Edition)
Java Deserialization Vulnerabilities - The Forgotten Bug Class (RuhrSec Edition)Java Deserialization Vulnerabilities - The Forgotten Bug Class (RuhrSec Edition)
Java Deserialization Vulnerabilities - The Forgotten Bug Class (RuhrSec Edition)
 
Burp Plugin Development for Java n00bs - 44CON 2012
Burp Plugin Development for Java n00bs - 44CON 2012Burp Plugin Development for Java n00bs - 44CON 2012
Burp Plugin Development for Java n00bs - 44CON 2012
 
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
 
Java Concurrency Quick Guide
Java Concurrency Quick GuideJava Concurrency Quick Guide
Java Concurrency Quick Guide
 
Fixing the Java Serialization Mess
Fixing the Java Serialization Mess Fixing the Java Serialization Mess
Fixing the Java Serialization Mess
 
Exploiting Deserialization Vulnerabilities in Java
Exploiting Deserialization Vulnerabilities in JavaExploiting Deserialization Vulnerabilities in Java
Exploiting Deserialization Vulnerabilities in Java
 
JRuby in Java Projects
JRuby in Java ProjectsJRuby in Java Projects
JRuby in Java Projects
 
Hibernate introduction
Hibernate introductionHibernate introduction
Hibernate introduction
 
Java Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsJava Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and Trends
 
Using Java from Ruby with JRuby IRB
Using Java from Ruby with JRuby IRBUsing Java from Ruby with JRuby IRB
Using Java from Ruby with JRuby IRB
 
CS6270 Virtual Machines - Java Virtual Machine Architecture and APIs
CS6270 Virtual Machines - Java Virtual Machine Architecture and APIsCS6270 Virtual Machines - Java Virtual Machine Architecture and APIs
CS6270 Virtual Machines - Java Virtual Machine Architecture and APIs
 
JVM for Dummies - OSCON 2011
JVM for Dummies - OSCON 2011JVM for Dummies - OSCON 2011
JVM for Dummies - OSCON 2011
 
Jvm Architecture
Jvm ArchitectureJvm Architecture
Jvm Architecture
 
Java performance tuning
Java performance tuningJava performance tuning
Java performance tuning
 
Wt unit 3 server side technology
Wt unit 3 server side technologyWt unit 3 server side technology
Wt unit 3 server side technology
 

Destacado

Destacado (6)

Garbage collection in java
Garbage collection in javaGarbage collection in java
Garbage collection in java
 
5 Coding Hacks to Reduce GC Overhead
5 Coding Hacks to Reduce GC Overhead5 Coding Hacks to Reduce GC Overhead
5 Coding Hacks to Reduce GC Overhead
 
Garbage Collection in Java
Garbage Collection in JavaGarbage Collection in Java
Garbage Collection in Java
 
An efficient memory system for java Garbage Collection
An efficient memory system for java Garbage CollectionAn efficient memory system for java Garbage Collection
An efficient memory system for java Garbage Collection
 
[BGOUG] Java GC - Friend or Foe
[BGOUG] Java GC - Friend or Foe[BGOUG] Java GC - Friend or Foe
[BGOUG] Java GC - Friend or Foe
 
Garbage collection
Garbage collectionGarbage collection
Garbage collection
 

Similar a Javasession10

Lecture 2 Java Virtual Machine .pptx
Lecture 2 Java Virtual Machine .pptxLecture 2 Java Virtual Machine .pptx
Lecture 2 Java Virtual Machine .pptx
AnupamKumar559254
 
02D-Memory Management in Java.pptx
02D-Memory Management in Java.pptx02D-Memory Management in Java.pptx
02D-Memory Management in Java.pptx
AnhNhatNguyen5
 
Inside The Java Virtual Machine
Inside The Java Virtual MachineInside The Java Virtual Machine
Inside The Java Virtual Machine
elliando dias
 
Quick introduction to Java Garbage Collector (JVM GC)
Quick introduction to Java Garbage Collector (JVM GC)Quick introduction to Java Garbage Collector (JVM GC)
Quick introduction to Java Garbage Collector (JVM GC)
Marcos García
 
Tomcatx troubleshooting-production
Tomcatx troubleshooting-productionTomcatx troubleshooting-production
Tomcatx troubleshooting-production
Vladimir Khokhryakov
 
Garbage Collection, Tuning And Monitoring JVM In EBS 11i And R12
Garbage Collection, Tuning And Monitoring JVM In EBS 11i And R12Garbage Collection, Tuning And Monitoring JVM In EBS 11i And R12
Garbage Collection, Tuning And Monitoring JVM In EBS 11i And R12
sidg75
 

Similar a Javasession10 (20)

Efficient Memory and Thread Management in Highly Parallel Java Applications
Efficient Memory and Thread Management in Highly Parallel Java ApplicationsEfficient Memory and Thread Management in Highly Parallel Java Applications
Efficient Memory and Thread Management in Highly Parallel Java Applications
 
Performance Tuning - Memory leaks, Thread deadlocks, JDK tools
Performance Tuning -  Memory leaks, Thread deadlocks, JDK toolsPerformance Tuning -  Memory leaks, Thread deadlocks, JDK tools
Performance Tuning - Memory leaks, Thread deadlocks, JDK tools
 
Java programing considering performance
Java programing considering performanceJava programing considering performance
Java programing considering performance
 
Lecture 2 Java Virtual Machine .pptx
Lecture 2 Java Virtual Machine .pptxLecture 2 Java Virtual Machine .pptx
Lecture 2 Java Virtual Machine .pptx
 
Efficient Memory and Thread Management in Highly Parallel Java Applications
Efficient Memory and Thread Management in Highly Parallel Java ApplicationsEfficient Memory and Thread Management in Highly Parallel Java Applications
Efficient Memory and Thread Management in Highly Parallel Java Applications
 
Garbage Collection in Java.pdf
Garbage Collection in Java.pdfGarbage Collection in Java.pdf
Garbage Collection in Java.pdf
 
Java Garbage Collection - How it works
Java Garbage Collection - How it worksJava Garbage Collection - How it works
Java Garbage Collection - How it works
 
Java memory model
Java memory modelJava memory model
Java memory model
 
02D-Memory Management in Java.pptx
02D-Memory Management in Java.pptx02D-Memory Management in Java.pptx
02D-Memory Management in Java.pptx
 
JVM Performance Tuning
JVM Performance TuningJVM Performance Tuning
JVM Performance Tuning
 
Java JVM
Java JVMJava JVM
Java JVM
 
Inside The Java Virtual Machine
Inside The Java Virtual MachineInside The Java Virtual Machine
Inside The Java Virtual Machine
 
Quick introduction to Java Garbage Collector (JVM GC)
Quick introduction to Java Garbage Collector (JVM GC)Quick introduction to Java Garbage Collector (JVM GC)
Quick introduction to Java Garbage Collector (JVM GC)
 
Android Memory , Where is all My RAM
Android Memory , Where is all My RAM Android Memory , Where is all My RAM
Android Memory , Where is all My RAM
 
An Introduction to JVM Internals and Garbage Collection in Java
An Introduction to JVM Internals and Garbage Collection in JavaAn Introduction to JVM Internals and Garbage Collection in Java
An Introduction to JVM Internals and Garbage Collection in Java
 
Tomcatx troubleshooting-production
Tomcatx troubleshooting-productionTomcatx troubleshooting-production
Tomcatx troubleshooting-production
 
jvm.pptx
jvm.pptxjvm.pptx
jvm.pptx
 
Garbage Collection, Tuning And Monitoring JVM In EBS 11i And R12
Garbage Collection, Tuning And Monitoring JVM In EBS 11i And R12Garbage Collection, Tuning And Monitoring JVM In EBS 11i And R12
Garbage Collection, Tuning And Monitoring JVM In EBS 11i And R12
 
Profiler Guided Java Performance Tuning
Profiler Guided Java Performance TuningProfiler Guided Java Performance Tuning
Profiler Guided Java Performance Tuning
 
Jvm is-your-friend
Jvm is-your-friendJvm is-your-friend
Jvm is-your-friend
 

Más de Rajeev Kumar (9)

Db performance optimization with indexing
Db performance optimization with indexingDb performance optimization with indexing
Db performance optimization with indexing
 
Jms intro
Jms introJms intro
Jms intro
 
Javasession8
Javasession8Javasession8
Javasession8
 
Javasession6
Javasession6Javasession6
Javasession6
 
Javasession7
Javasession7Javasession7
Javasession7
 
Javasession5
Javasession5Javasession5
Javasession5
 
Javasession4
Javasession4Javasession4
Javasession4
 
Java session 3
Java session 3Java session 3
Java session 3
 
Java session2
Java session2Java session2
Java session2
 

Último

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
Chris Hunter
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
heathfieldcps1
 

Último (20)

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 

Javasession10

  • 2. How Garbage collection works? • Java manages memory automatically • The Garbage collector is part of the Java virtual machine • Objects referenced by java variables are created in heap memory • As long as any variable references an object, it is retained. • When all references expire, the object is eligible to be garbage collected. • We can explicitly expire persistent objects by setting it to null • Variables local to function or code block expire when function is complete. • How Garbage collection works :  The garbage collector runs on its own thread. Mark and sweep approach  When garbage collector identifies a de-referenced object, it can destroy it and reclaim memory  You as the programmer cannot force garbage collection  Methods System.gc() and Runtim.gc() can request garbage collection, but there is no guarantee it will happen  If no memory is available for newly requested object, JVM throws OutOfMemoryError. • Tips for managing memory : Use command line options to manage amount of available heap memory • java –Xms256m HelloWorld initial heap size • Java –Xmx256m HelloWorld Maximum heap size • Java –Xmn256m HelloWorld Heap size for young generation objects.
  • 4. Java (JVM) Memory Types • Heap Memory : Heap memory is also called as shared memory. As this is the place where multiple threads will share the same data. The heap will be created at JVM startup and the size can be static or dynamic. The JVM specification mandates a Garbage Collection mechanism for reclaiming the memory of an object on the Java heap. The implementation of the Garbage Collector is not specified, but it is not allowed to provide the programmer with an explicit mechanism for deallocating the memory of an object. • Non-heap Memory : It comprises of ‘Method Area’ and other memory required for internal processing. So here the major player is ‘Method Area’. • Method Area : The method area is responsible for storing class information. The Class-Loader will load the bytecode of a class and will pass it to the JVM. The JVM will generate an internal class representation of the bytecode and store it in the method area. The internal representation of a class will have the following data areas: i. Runtime Constant Pool Numeric constants of the class of types int, long, float or double, String-constants and symbolic references to all methods, attributes and types of this class. ii. Method CodeThe implementation (code) of all methods of this class including constructors etc. iii. Attributes A list of all named attributes of this class. iv. FieldsValues of all fields of this class as references to the Runtime Constant Pool. • Memory Pool : Memory pools are created by JVM memory managers during runtime. Memory pool may belong to either heap or non-heap memory. • Runtime Constant Pool : A run time constant pool is a per-class or per-interface run time representation of the constant_pool table in a class file. Each runtime constant pool is allocated from the Java virtual machine’s method area. • Java Stacks or Frames : Java stacks are created private to a thread. Every thread will have a program counter (PC) and a java stack. PC will use the java stack to store the intermediate values, dynamic linking, return values for methods and dispatch exceptions. This is used in the place of registers.
  • 5. Memory Generations • HotSpot VM’s garbage collector uses generational garbage collection. It separates the JVM’s memory into and they are called young generation and old generation. • Young Generation : Young generation memory consists of two parts, Eden space and survivor space. Shortlived objects will be available in Eden space. Every object starts its life from Eden space. When GC happens, if an object is still alive and it will be moved to survivor space and other dereferenced objects will be removed. • Old Generation – Tenured and PermGen : Old generation memory has two parts, tenured generation and permanent generation (PermGen). PermGen is a popular term. We used to error like PermGen space not sufficient. GC moves live objects from survivor space to tenured generation. The permanent generation contains meta data of the virtual machine, class and method objects. • Local Variables are stored in Frames during runtime. • Static Variables are stored in Method Area. • Arrays are stored in heap memory. • Errors :  Javadoc of java.lang.OutOfMemoryError : Thrown when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector.  In the heap we get an OutOfMemoryError, if the garbage collector cannot reclaim enough memory for a new object. In such situation the Sun HotSpot JVM shows this error message: Exception in thread "main": java.lang.OutOfMemoryError: Java heap space  if the application tries to create an array on the heap that is bigger than the total heap size. error can be : Exception in thread "main": java.lang.OutOfMemoryError: Requested array size exceeds VM limit  If there is not enough memory in the method area for creating a new class, the Sun HotSpot implementation gets an error in the permanent generation:Exception in thread "main": java.lang.OutOfMemoryError: PermGen space
  • 6. • If there are too many threads in the JVM and there is not enough memory left to create a new thread. I’ve seen below error because the memory limits of a process have been reached (especially in 32bit operating systems, e.g. on Windows 32bit it is 2GB) or the maximum number of file handles for the user that executes the java process has been reached. Exception in thread "main" java.lang.OutOfMemoryError: unable to create new native thread • Memory allocation error on a native stack (JNI method call) : Exception in thread "main": java.lang.OutOfMemoryError: <reason> <stacktrace> (Native method) • It is also interesting that a memory allocation error on the JVM stack (too many frames on the stack) does not throw an Java OutOfMemory error but as the JVM specification mandates: java.lang.StackOverflowError. • If there is not enough memory left on the operating system level – which is normally true if other processes are using all of the available memory or the swap space is configured too small. Error: Exception in thread "main": java.lang.OutOfMemoryError: request <size> bytes for <reason>. Out of swap space?
  • 7. Java Memory Leaks • In Java objects get generated on the heap and live on as long as they are referenced. The garbage collector checks during it GC-phases if the object is still referenced – and does mark it as “garbage” and clean it up later when this is no longer the case (the actual behaviour differs for different gc-algorithms, like the Copying Collectors or Garbage-First, but is not of importance for understanding liveness). But not every reference is important for surviving, but only so called GC root references. Especially when understanding Memory Leaks, GC roots are a central concept to identify the important references to an object. Garbage Collector Roots are special objects which do not have incoming references and are responsible for keeping referenced objects alive. When an object cannot be reached directly or indirectly from a GC root, it will be marked as “unreachable” and made eligible for garbage collection. Simply speaking, there are three kinds of GC roots:  Temporary variables on the stack of a thread  Static members of a loaded class  Special native references from JNI • Usually there are tree types of issues with Java OutOfMemoryError problems in heap memory:  Objects, which can be reached via a GC root reference, but are actually no longer used by application code. Those are called Java Memory Leaks.  Too many or too large objects. So there is not enough heap available for the application to execute. Usually happens when there are large objects kept in cache like structures.  Too many temporary objects. So there is just for a short time not enough memory. Usually happens in load scenarios where many temporary objects are used.  Ex: http://ideone.com/1QowAQ
  • 8. Java Memory Leaks • Java Memory Leaks occur when objects still have a GC root reference, but are not actually used anymore. Those “Loitering Objects” stay around for the whole life of the JVM. If the application is creating those “dead objects” on and on, the memory will be filled up and eventually result in a java.lang.OutOfMemoryError. Typical causes are static collections, which are used as a kind of cache. Usually objects are added, but never removed (Let’s face it: How often have you used add() and put() and how often used remove() methods?). Because the objects are referenced by the static collection, they cannot be freed up anymore, as the collection has a GC root reference via the classloader. • Depending on the creation frequency and the object size, as well as the size of the Java heap, the OutOfMemoryError occurs sooner or later. Especially those “creeping memory leaks” can be found in many applications, but are usually “ignored” by: • Using large heaps to delay the error. Happens frequently nowadays, as the old 32bit memory limit has vanished through the usage of 64 bit JVMs. • Restarting the application server during the night. This “resets” the memory usage. If the memory leak takes longer than 24 hours to become severe, this will help. • But both variants are dangerous, as they have negative impact on the system performance and are heavily influenced by the system usage. A change in usage or more “traffic” can produce the error faster than expected. Garbage collection times also have a negative effect on the application performance, as the increasing “tenured generation” causes longer “Mark”-Phases during garbage collection, resulting in longer pause times, which can be observed as system hangs. • Refer: https://gist.github.com/rajeevprasanna/04b4c9322a5245877c1f