Java heap space ram

JVM изнутри – организация памяти внутри процесса Java

Наверное, все, работающие с Java, знают об управлении памяти на уровне, что для ее распределения используется сборщик мусора. Не все, к сожалению, знают, как именно этот сборщик (-и) работает, и как именно организована память внутри процесса Java.

Из-за этого иногда делается неверный вывод, что memory leaks в Java не бывает, и слишком задумываться о памяти не надо. Так же часто идут холивары по поводу чрезмерного расхода памяти.
Все описанное далее относится к Sun-овской реализации JVM (HotSpot), версий 5.0+, конкретные детали и алгоритмы могут различаться для разных версий.

Итак, память процесса различается на heap (куча) и non-heap (стек) память, и состоит из 5 областей (memory pools, memory spaces):
• Eden Space (heap) – в этой области выделятся память под все создаваемые из программы объекты. Большая часть объектов живет недолго (итераторы, временные объекты, используемые внутри методов и т.п.), и удаляются при выполнении сборок мусора это области памяти, не перемещаются в другие области памяти. Когда данная область заполняется (т.е. количество выделенной памяти в этой области превышает некоторый заданный процент), GC выполняет быструю (minor collection) сборку мусора. По сравнению с полной сборкой мусора она занимает мало времени, и затрагивает только эту область памяти — очищает от устаревших объектов Eden Space и перемещает выжившие объекты в следующую область.
• Survivor Space (heap) – сюда перемещаются объекты из предыдущей, после того, как они пережили хотя бы одну сборку мусора. Время от времени долгоживущие объекты из этой области перемещаются в Tenured Space.
• Tenured (Old) Generation (heap) — Здесь скапливаются долгоживущие объекты (крупные высокоуровневые объекты, синглтоны, менеджеры ресурсов и проч.). Когда заполняется эта область, выполняется полная сборка мусора (full, major collection), которая обрабатывает все созданные JVM объекты.
• Permanent Generation (non-heap) – Здесь хранится метаинформация, используемая JVM (используемые классы, методы и т.п.). В частноси
• Code Cache (non-heap) — эта область используется JVM, когда включена JIT-компиляция, в ней кешируется скомпилированный платформенно — зависимый код.

Читайте также:  Write number in expanded form java

Вот тут — blogs.sun.com/vmrobot/entry/основы_сборки_мусора_в_hotspot есть хорошее описание работы сборщиков мусора, перепечатывать не вижу смысла, советую всем интересующимся ознакомиться подробней по ссылке.

Статья не моя. но камрада Zorkus’a, который хотел бы получить инвайт :).

Источник

Java Heap Space vs Stack — Memory Allocation in Java

Java Heap Space vs Stack - Memory Allocation in Java

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Sometime back I wrote a couple of posts about Java Garbage Collection and Java is Pass by Value. After that I got a lot of emails to explain about Java Heap Space, Java Stack Memory, Memory Allocation in Java and what are the differences between them. You will see a lot of reference to Heap and Stack memory in Java, Java EE books and tutorials but hardly complete explanation of what is heap and stack memory in terms of a program.

Java Heap Space

Java Heap space is used by java runtime to allocate memory to Objects and JRE classes. Whenever we create an object, it’s always created in the Heap space. Garbage Collection runs on the heap memory to free the memory used by objects that don’t have any reference. Any object created in the heap space has global access and can be referenced from anywhere of the application.

Java Stack Memory

Java Stack memory is used for the execution of a thread. They contain method-specific values that are short-lived and references to other objects in the heap that is getting referred from the method. Stack memory is always referenced in LIFO (Last-In-First-Out) order. Whenever a method is invoked, a new block is created in the stack memory for the method to hold local primitive values and reference to other objects in the method. As soon as the method ends, the block becomes unused and becomes available for the next method. Stack memory size is very less compared to Heap memory.

Heap and Stack Memory in Java Program

package com.journaldev.test; public class Memory < public static void main(String[] args) < // Line 1 int i=1; // Line 2 Object obj = new Object(); // Line 3 Memory mem = new Memory(); // Line 4 mem.foo(obj); // Line 5 >// Line 9 private void foo(Object param) < // Line 6 String str = param.toString(); //// Line 7 System.out.println(str); >// Line 8 > 

java memory management, java heap space, heap vs stack, java heap, stack vs heap

The below image shows the Stack and Heap memory with reference to the above program and how they are being used to store primitive, Objects and reference variables. Let’s go through the steps of the execution of the program.

  • As soon as we run the program, it loads all the Runtime classes into the Heap space. When the main() method is found at line 1, Java Runtime creates stack memory to be used by main() method thread.
  • We are creating primitive local variable at line 2, so it’s created and stored in the stack memory of main() method.
  • Since we are creating an Object in the 3rd line, it’s created in heap memory and stack memory contains the reference for it. A similar process occurs when we create Memory object in the 4th line.
  • Now when we call the foo() method in the 5th line, a block in the top of the stack is created to be used by the foo() method. Since Java is pass-by-value, a new reference to Object is created in the foo() stack block in the 6th line.
  • A string is created in the 7th line, it goes in the String Pool in the heap space and a reference is created in the foo() stack space for it.
  • foo() method is terminated in the 8th line, at this time memory block allocated for foo() in stack becomes free.
  • In line 9, main() method terminates and the stack memory created for main() method is destroyed. Also, the program ends at this line, hence Java Runtime frees all the memory and ends the execution of the program.

Difference between Java Heap Space and Stack Memory

Based on the above explanations, we can easily conclude the following differences between Heap and Stack memory.

  1. Heap memory is used by all the parts of the application whereas stack memory is used only by one thread of execution.
  2. Whenever an object is created, it’s always stored in the Heap space and stack memory contains the reference to it. Stack memory only contains local primitive variables and reference variables to objects in heap space.
  3. Objects stored in the heap are globally accessible whereas stack memory can’t be accessed by other threads.
  4. Memory management in stack is done in LIFO manner whereas it’s more complex in Heap memory because it’s used globally. Heap memory is divided into Young-Generation, Old-Generation etc, more details at Java Garbage Collection.
  5. Stack memory is short-lived whereas heap memory lives from the start till the end of application execution.
  6. We can use -Xms and -Xmx JVM option to define the startup size and maximum size of heap memory. We can use -Xss to define the stack memory size.
  7. When stack memory is full, Java runtime throws java.lang.StackOverFlowError whereas if heap memory is full, it throws java.lang.OutOfMemoryError: Java Heap Space error.
  8. Stack memory size is very less when compared to Heap memory. Because of simplicity in memory allocation (LIFO), stack memory is very fast when compared to heap memory.

That’s all for Java Heap Space vs Stack Memory in terms of java application, I hope it will clear your doubts regarding memory allocation when any java program is executed.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Источник

Java Guide: What is Heap Space & Dynamic Memory Allocation?

Java Guide: What is Heap Space & Dynamic Memory Allocation?

To run Java applications optimally, the JVM divides memory into stack and heap memory. Whenever new variables and objects are declared, new methods are called or other similar operations are performed, the JVM designates memory to these operations from either the Stack Memory or Heap Space.

Heap space is used for the dynamic memory allocation of Java objects and classes at runtime. New objects are always created in the heap space, and references to these objects are stored in the stack memory.

Java Heap Space and Generations

The heap space is created by the JVM when it starts. The heap is used as long as the application is running. It can be broken down into smaller parts called generations, which are:

  • Young Generation — All new objects are allocated and aged here. A minor garbage collection occurs when this fills up.
  • Old or Tenured Generation — Long surviving objects are stored here. When objects are stored in the Young Generation, a threshold for the object’s age is set. When this threshold is reached, the object is moved to the Old Generation. Garbage collection is usually performed in the Old Generation when it’s full. This is called Major GC and it usually takes longer.
  • Permanent Generation (replaced by Metaspace since Java 8) — Consists of JVM metadata for runtime classes and application methods.

Java Heap Space Features

Some features of the heap space are:

  • It is accessed via complex management techniques that include the Young, Old and Permanent Generations.
  • Access to the heap is slower than to the stack memory.
  • The heap is not automatically deallocated. It needs the Garbage Collector to free up unused objects to keep memory usage efficient.
  • The heap is not threadsafe and needs to be guarded by keeping the code properly synchronized.

Java Heap Size

Referenced Java objects remain active in the heap throughout their lifespan and occupy memory. These objects are globally accessible from anywhere in the application. When objects are no longer referenced, they become eligible for garbage collection to free up the occupied heap memory.

The Java heap size is determined by two JVM attributes, which can be set when launching the application:

If an object requires more memory than is available in the heap, the application can encounter an OutOfMemoryError . To learn more about how to solve an OutOfMemoryError , check https://rollbar.com/blog/how-to-handle-outofmemoryerror-exceptions-in-java/.

Java Heap Space Example

Here’s an example of how memory is allocated in the Java Heap Space using a simple program:

class Vehicle < private String make; public String getMake() < return make; > public void setMake(String make) < this.make = make; > > public class JavaHeapSpaceExample < public static void main(String[] args) < String make = "Audi"; Vehicle vehicle = new Vehicle(); vehicle.setMake(make); System.out.println("Make = " + vehicle.getMake()); > >

When the above code is executed, all the runtime classes are loaded into the heap space. The JRE creates stack memory to be used by the main() method thread when it is found.

The string created on line 15 is stored in the String Pool in the heap space. The reference variable for the string is stored in the stack memory. The reference variable vehicle of the type Vehicle is also created in stack memory, which points to the actual object in the heap.

The heap memory stores the instance variables for the object vehicle of type Vehicle .

On line 19, the main() method terminates and the stack memory created for it is destroyed. Since the program ends here, the JRE frees up all memory and ends program execution.

Conclusion

Based on the above explanations, the following can be concluded about the Java Heap Space and how it works across these various aspects:

  • Application — The entire application uses the Heap Space during runtime.
  • Size — There are no size limits on the Heap. The -Xms and -Xmx JVM attributes can be used to define the startup size and maximum size of the heap memory.
  • Storage — All newly created objects are stored in the Heap.
  • Object Scope — Objects stored in the Heap are globally accessible.
  • Memory Access — The Heap is accessed via complex memory management techniques that include the Young, Old and Permanent Generations.
  • Life — Heap Space exists as long as the application runs.
  • Efficiency — Heap Space is slower to allocate compared to the stack.
  • Allocation/Deallocation — Heap Space is allocated when new objects are created and deallocated by the Garbage Collector when they are no longer referenced.

Track, Analyze and Manage Errors With Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Java errors easier than ever. Sign Up Today!

Источник

Оцените статью