Jvm memory settings in a container environment

FAQ Maximum Java Heap Space on 32 and 64 bit JVM

Here is a list of some confusions I have seen on Java programmers regarding
maximum heap space of 32 and 64 bit Java Virtual Machines :

  1. What is the maximum heap
    size for 32 bit JVM?2GB or 4GB?
  2. Why my JVM not able to
    start on windows when maximum heap space around 1600M?
  3. Why Linux or Solaris
    allow more maximum heap size than windows for same, 32 bit JVM?
  4. Can we set more than
    4GB as maximum heap size for 32 bit JVM running on 64 bit or x64 operating system?
  5. What is maximum heap
    size for 64 bit or x64 JVM, Is it 8GB or 16GB?
  6. Can I specify more
    than 1GB as heap space if physical memory is less than 1GB?

If you also have similar confusion on JVM maximum heap space no
matter whether it’s for your own Java application or any Java web or application server like Tomcat, JBoss or WebLogic, This discussion applies to all of them.

What is
maximum heap size for 32 bit JVM?2GB or
4GB?

This confusion comes because of a sign bit, many programmers think in terms
of signed integer and they think maximum addressable memory (size of address
bus) for 32-bit architecture is 2^32-1 or 2GB
and this confusion is supported by fact that you can not provide maximum
heap space as 2GB on a windows machine. But this is wrong. Memory is nothing to
do with a signed or unsigned bit as there is no negative memory address. So the theoretical limit for maximum heap size on 32 bit JVM is 4GB and for 64 bit JVM
it’s 2^64.

Why JVM
not able to start on Windows XP when maximum heap space around 1600M?

This problem is most obvious on Windows platforms like Windows XP, which
tries to allocate a contiguous chunk of memory as requested by -Xmx JVM parameters. Windows
reserves some space for his own and seems also allocate memory around half of memory address bar, which consequently reduces contiguous memory space
somewhere less than 2GB, around 1500 to 1600M and when you give more than this
size, JVM throws an error as.

Could not create the Java virtual machine.

Invalid initial heap size: -Xms1.5G

Remember, this limit on heap space is due to the Windows operating system’s
own behavior. You can set maximum heap space, more than this size in Linux or
Solaris. Though maximum heap size for 32 bit or 64 bit JVM will always be less
than the theoretical limit of addressable memory. By the way, you can get this error
due to many reasons, see How to fix Invalid Initial and Maximum heap size in JVM for more details.

Why Linux
or Solaris allow more maximum heap size than windows for same, 32 bit JVM?

This point is also related to the second. Though there could be multiple reasons for that I think It could be
because of Windows trying to allocate a contiguous chunk of memory as Java heap
space. Happy to hear your opinion on this.

Can we
set more than 4GB as maximum heap size for 32 bit JVM running on 64 bit or x64
operating system?

This is a tricky question as you are
running 32 bit JVM on the x64 server. In my opinion, you can set up to 4GB for 32 bit
JVM but not more than that. Though x64 Servers has more memory for his needs
and since every process can have up to 2^64 bit it may
look perfectly OK for 32 bit JVM to accept 4GB
as maximum heap size
. In practice, I have tried both Linux and Solaris
servers setting the maximum heap size as 4G but it didn’t accept. Solaris goes closer to 4GB by allowing up to 3.6G (approx).

What is
maximum heap size for 64 bit or x64 JVM, Is it 8GB or 16GB?

This question mostly arises because of available physical memory on the machine. As no system currently have 2^64 bit of
physical memory or RAM and often high-end servers have memory around 8G, 16GB or
32GB. Theoretical maximum memory for x64 machines is 2^64 bit but again it depends on how much your operating systems allow. I read somewhere
that Windows allowed a maximum of 32GB for 64 bit JVM.

Can I
specify more than 1GB as heap space if physical memory is less than 1GB?

Theoretically yes, because the operating systems can use virtual memory and
swap pages between physical memory and virtual memory when there is no room in
physical memory. Practically, if you are running on windows then it depends on how
far you can go, I have run Java program with -Xmx1124M even though
my machine has less than 1GB RAM.

That’s all on what is maximum Java heap space for 32 bit and 64 bit
JVM
. As you see maximum heap size depends upon the host operating system. Solaris and Linux provide more heap space than windows and that could be one
of the many reasons that Java Server application mostly runs on UNIX based
systems. Let me know what’s your thought and experienceon maximum Java heap space forx86 and x64 JVM running on both x86 and x64
machines.

Other Java JVM Tutorials from Javarevisited Blog

Убунту

Это среда тестирования:

OS  : Ubuntu 13 (64 bits) (Under VirtualBox)
RAM : 4G
CPU : 1 x Processors
JDK : 1.7.0_51
$ java -XX:+PrintFlagsFinal -version | grep -iE 'HeapSize|PermSize|ThreadStackSize'
            
    uintx InitialHeapSize                          := 64781184        {product}   
    uintx MaxHeapSize                              := 1038090240      {product} 
    uintx PermSize                                  = 21757952        {pd product}
    uintx MaxPermSize                               = 174063616       {pd product}
     intx ThreadStackSize                           = 1024            {pd product}          
java version "1.7.0_51"
OpenJDK Runtime Environment (IcedTea 2.4.4) (7u51-2.4.4-0ubuntu0.13.10.1)
OpenJDK 64-Bit Server VM (build 24.45-b08, mixed mode)

В описанной выше среде JVM выделила следующие значения по умолчанию:

  1. Размер кучи Java байт (61,7 М) и байт (990 М).
  2. Размер PermGen байт (20,75 М), байт (166 М)
  3. Размер стека потоков килобайт (1 м)

Выделенный объем памяти кучи довольно близок к результату эргономики.

#ergonomics algorithm 
Initial heap size = 4096M/64 = 64M
Maximum heap size = 4096M/4 = 1024M

Summary

  • Always try to replace with Trove , with a and finally, with a Trove . Such replacement requires adding a single letter to your code (letter ‘T’) and no other code changes except the import statement. Such replacement will give you significant memory savings – see table below.
  • The following table summarizes the storage occupied per stored value assuming that a reference occupies 4 bytes. Note that you must spend 4 byte per reference in any case, so subtract 4 bytes from the values in the following table to find out the storage overhead (subtract 8 bytes for maps, because there is a key as well as a value).
JDK collection Size Possible Trove substitution Size
32 * SIZE + 4 * CAPACITY bytes 8 * CAPACITY bytes
32 * SIZE + 4 * CAPACITY bytes 4 * CAPACITY bytes
40 * SIZE + 4 * CAPACITY bytes None  
32 * SIZE + 4 * CAPACITY bytes 8 * CAPACITY bytes
40 * SIZE bytes None  
4 * CAPACITY bytes None  

Обзор памяти Java

Краткий обзор структуры памяти Java:

1. Размер кучи Java Место для хранения объектов, созданных вашим Java-приложением, здесь происходит сборка мусора, память, используемая вашим Java-приложением. Для тяжелого процесса Java недостаточный размер кучи приведет к популярному .

-Xms - Set initial Java heap size
-Xmx - Set maximum Java heap size

$ java -Xms512m -Xmx1024m JavaApp

2. Размер пермского поколения Место для хранения загруженного определения класса и метаданных. Если загружен большой проект с базой кода, недостаточный размер PermGen приведет к популярному .

-XX:PermSize - Set initial PermGen Size.
-XX:MaxPermSize - Set the maximum PermGen Size.

$ java -XX:PermSize=64m -XX:MaxPermSize=128m JavaApp

3. Размер стека Java Размер потока Java. Если в проекте обрабатывается много потоков, попробуйте уменьшить размер этого стека, чтобы избежать нехватки памяти. – Xss размер стека потоков java

$ java -Xss512k JavaApp

Changing To a Different JVM

When you create a domain, if you choose to customize the configuration, the Configuration Wizard presents a list of SDKs that WebLogic Server installed. From this list, you choose the JVM that you want to run your domain and the wizard configures the BEA start scripts based on your choice. After you create a domain, if you want to use a different JVM, you can modify the scripts as follows. For more information, see «» .

JVM Heap Size and Garbage Collection

Garbage collection is the JVM’s process of freeing up unused Java objects in the Java heap.The Java heap is where the objects of a Java program live. It is a repository for live objects, dead objects, and free memory. When an object can no longer be reached from any pointer in the running program, it is considered «garbage» and ready for collection.

The JVM heap size determines how often and how long the VM spends collecting garbage. An acceptable rate for garbage collection is application-specific and should be adjusted after analyzing the actual time and frequency of garbage collections. If you set a large heap size, full garbage collection is slower, but it occurs less frequently. If you set your heap size in accordance with your memory needs, full garbage collection is faster, but occurs more frequently.

The goal of tuning your heap size is to minimize the time that your JVM spends doing garbage collection while maximizing the number of clients that WebLogic Server can handle at a given time. To ensure maximum performance during benchmarking, you might set high heap size values to ensure that garbage collection does not occur during the entire run of the benchmark.

You might see the following Java error if you are running out of heap space:

To modify heap space values, see .

To configure WebLogic Server to detect automatically when you are running out of heap space and to address low memory conditions in the server, see .

The Heap and the Nursery

Java objects reside in an area called the heap. The heap is created when the JVM starts up and may increase or decrease in size while the application runs. When the heap becomes full, garbage is collected. During the garbage collection objects that are no longer used are cleared, thus making space for new objects.

Note that the JVM uses more memory than just the heap. For example Java methods, thread stacks and native handles are allocated in memory separate from the heap, as well as JVM internal data structures.

The heap is sometimes divided into two areas (or generations) called the nursery (or young space) and the old space. The nursery is a part of the heap reserved for allocation of new objects. When the nursery becomes full, garbage is collected by running a special young collection, where all objects that have lived long enough in the nursery are promoted (moved) to the old space, thus freeing up the nursery for more object allocation. When the old space becomes full garbage is collected there, a process called an old collection.

The reasoning behind a nursery is that most objects are temporary and short lived. A young collection is designed to be swift at finding newly allocated objects that are still alive and moving them away from the nursery. Typically, a young collection frees a given amount of memory much faster than an old collection or a garbage collection of a single-generational heap (a heap without a nursery).

In R27.2.0 and later releases, a part of the nursery is reserved as a keep area. The keep area contains the most recently allocated objects in the nursery and is not garbage collected until the next young collection. This prevents objects from being promoted just because they were allocated right before a young collection started.

HashMap, THashMap

is the most popular map in JDK. Provided that it contains objects with a quality method and it has not too high load factor, it will generally give you performance of and methods (as well as similar methods like ).

is built on top of the array of objects. The implementation ensures that this array length is always equal to at least . Default load factor for is 0.75 and default capacity is 16. Load factor specifies which part of an array could be used for storage and is a value between 0 and 1. The higher is the load factor, the less space is being wasted, but starts to work slower due to increased rate of collisions. The smaller if the load factor, the more memory is wasted, but the performance of a is increasing due to smaller possibility of collisions.

So, as you have seen, the default () size of array of entries is 16 / 0.75 = 21.33 ~ 22.

What is a ? It contains a key, a value, hash of a key and a pointer to the next entry (remember that entries array could be sparse). It means that an entry occupies 32 bytes (12 bytes header + 16 bytes data + 4 bytes padding). So, a with size = S has to spend 32 * S bytes for entries storage. Besides, it will use 4 * C bytes for entries array, where C is the map capacity.

As you can see, if you will make the map capacity small enough (less than 12.5%), its entry array size will start dominating over the entries.

A instance will occupy 32 * SIZE + 4 * CAPACITY bytes, while the theoretical map size limit could be equal to bytes (2 arrays of keys and values with no space wasted). Of course, such a “map” will require O(N) lookup time in general case. Though, in special cases, for example for it could be as low as .

Can we improve the hash map memory consumption without sacrificing lookup/add times? Surely, we can. Trove is a replacement implementation for . Internally contains 2 arrays – one for keys, another for values. It means that needs 8 * CAPACITY bytes for storage. Its default load factor is 0.5, but you can increase it if necessary.

Let’s compare the memory usage of and with default load factors and size = 100. capacity will be 134 (100/0.75) and capacity will be 200 (100/0.5). The total memory consumption of a will be (not including the memory occupied by keys or values!). The memory consumption of will be . Furthermore, if we will set load factor to 0.75 (thus making it equal to load factor), memory consumption will go down to .

As you can see, it worth to replace JDK with Trove if you want to save some memory.

HashSet, THashSet

JDK is built on top of a , where value is a singleton ‘present’ object. It means that the memory consumption of a is identical to : in order to store SIZE values, you need 32 * SIZE + 4 * CAPACITY bytes (plus size of your values). It is definitely not a memory-friendly collection.

Trove could be the easiest replacement collection for a – it implements and , which means you should just update a single letter in the initialization of your set.

uses a single object array for its values, so it uses 4 * CAPACITY bytes for storage. As you can see, compared to JDK , you will save 32 * SIZE bytes in case of the identical load factor, which is a huge improvement.

Предлагаемые для Java Memory

Ниже, я привел мою рекомендацию (параметры) для малой и средней нагрузки приложений Java

Heap = -Xms512m -Xmx1024mPermGen = -XX:PermSize=64m -XX:MaxPermSize=128mThread = -Xss512k

P.S: Для большинства проектов Java, 512k памяти для потока (thread) более чем достаточно.

оптимаьные значения для Java Heap Memory Size

Часто задаваемые вопросы.

какая -version?Избегайте жалоб от компилятора Java, заменить «-version» с вашим именем приложения Java.

Что это -XX:+PrintCommandLineFlags?Это -XX:+PrintCommandLineFlags  используется для вывода значения,только для изменения VM  (обозначается так: = символ).

How we Tested

Tests were run with Azul JDK 8 and OpenJDK 10 on a 32 GB MacBook Pro (15-inch, 2018).

$ use-java10JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk-10.0.2.jdk/Contents/Home$ java -versionopenjdk version "10.0.2" 2018-07-17OpenJDK Runtime Environment 18.3 (build 10.0.2+13)OpenJDK 64-Bit Server VM 18.3 (build 10.0.2+13, mixed mode)$ use-java8JAVA_HOME=/Library/Java/JavaVirtualMachines/zulu-8.jdk/Contents/Home$ java -versionopenjdk version "1.8.0_181"OpenJDK Runtime Environment (Zulu 8.31.0.1-macosx) (build 1.8.0_181-b02)OpenJDK 64-Bit Server VM (Zulu 8.31.0.1-macosx) (build 25.181-b02, mixed mode)

Results may depend on JVM versions and vendors.

Using WebLogic Startup Scripts to Set Heap Size

Sample startup scripts are provided with the WebLogic Server distribution for starting the server and for setting the environment to build and run the server:

  • and (Windows).
  • and (UNIX and Windows. On Windows, these scripts support the MKS and Cygnus BASH UNIX shell emulators.)

If you used the Configuration Wizard to create your domain, the WebLogic startup scripts are located in the domain-name directory where you specified your domain. By default, this directory is BEA_HOMEdomain-name, where BEA_HOME is the directory that contains the product installation, and domain-name is the name of the domain directory defined by the selected configuration template. For more information about creating domains using the Configuration Wizard, see «Creating Domains Using the Configuration Wizard» .

The WebLogic startup scripts set environment variables, such as the default memory arguments passed to Java (that is, heap size) and the location of the JDK, and then start the JVM with WebLogic Server arguments. Be aware that the WebLogic Server startup scripts specify default heap size parameters; therefore, you need to modify them to fit your environment and applications. For instructions on how to modifying the startup scripts to set the Java heap size options, see «» .

Окна

В Windows нет , вместо этого мы используем .

Это среда тестирования:

OS  : Windows 8
RAM : 16G
CPU : 8 x Processors
JDK : 1.7.0_40
C:\>java -XX:+PrintFlagsFinal -version | findstr /i "HeapSize PermSize ThreadStackSize"
    
    uintx InitialHeapSize                          := 266634176       {product}
    uintx MaxHeapSize                              := 4267704320      {product}
    uintx PermSize                                  = 21757952        {pd product}
    uintx MaxPermSize                               = 85983232        {pd product}
     intx ThreadStackSize                           = 0               {pd product}
java version "1.7.0_40"
Java(TM) SE Runtime Environment (build 1.7.0_40-b43)
Java HotSpot(TM) 64-Bit Server VM (build 24.0-b56, mixed mode)
  1. Размер кучи Java байт (256 м) и байт (4068 м).
  2. Размер PermGen байт (20,75 М), байт (823.М).
  3. Размер стека Java килобайт. (странно…)

Выделенный объем памяти кучи почти совпадает с результатом эргономики:

#ergonomics algorithm
Initial heap size = 16384/64 = 256M
Maximum heap size = 16384/4 = 4096M

Choosing a Garbage Collection Scheme

Depending on which JVM you are using, you can choose from several garbage collection schemes to manage your system memory. For example, some garbage collection schemes are more appropriate for a given type of application. Once you have an understanding of the workload of the application and the different garbage collection algorithms utilized by the JVM, you can optimize the configuration of the garbage collection.

Refer to the following links for in-depth discussions of garbage collection options for your JVM:

  • For an overview of the garbage collection schemes available with Sun’s HotSpot VM, see Tuning Garbage Collection with the 1.4.2 Java Virtual Machine.
  • For a comprehensive explanation of the collection schemes available with JDK 1.4.1, see Improving Java Application Performance and Scalability by Reducing Garbage Collection Times and Sizing Memory Using JDK 1.4.1, at
  • For a discussion of the garbage collection schemes available with the BEA WebLogic JRockit JVM, see WebLogic JRockit Documentation.
  • For some pointers about garbage collection from an HP perspective, see Tuning Garbage Collection with the 1.4.2 Java Virtual Machine.

Рекомендации

  1. Технический документ по управлению памятью Oracle
  2. Оракул, представляющий Постоянное поколение
  3. Эргономика в виртуальной машине Java 5.0
  4. Структура памяти JVM
  5. Хероку: Проблемы с памятью Java
  6. StackOverflow: Что такое “PermSize” в Java?
  7. Стековый поток: java.язык. Ошибка из памяти: Пространство PermGen
  8. Объяснение java.lang. Ошибка из памяти: Пространство PermGen
  9. Исключение JBoss Outofmemoryexception
  10. Параметры виртуальной машины Java HotSpot
  11. -XX:+Печать финала
  12. Полезные флаги JVM – Часть 3 (Печать всех флагов XX и их значений)
  13. Проверка параметров JVM точки доступа
  14. OpenJDK – глобальный исходный код

Оригинал: “https://mkyong.com/java/find-out-your-java-heap-memory-size/”

Body

One of the most common questions asked in WebSphere Java support is, «What is the recommended Maximum Heap size?»

One of the most common problems reported in WebSphere Java support is, «OutofMemory» condition (Java or Native).

This blog is simply a starting point or general reference based upon daily observations in the technical support arena, it is not intended to be a solution for every situation, but moreover a general set of starting recommendations.

Ideally, you will need to test appropriate values in your own environments and topologies, based upon application architecture, number of applications running, how busy the AppServer is and underlying load conditions, how much physical memory or RAM is installed and running, how many JVMs are being hosted and what other additional Java and native memory processes are running on the same machine.

For 32 bit platforms and Java stacks in general, the recommended Maximum Heap range for WebSphere Application Server (WAS), would be between (1024M — 1536M) or (1G — 1.5G); higher values will most likely eventually result in Native Memory contention. For Node Agents and Deployment Manager, depending upon how many nodes are managed serviced and how many application deployments occur, you can probably utilize less heap memory, between (512M — 1024M) or (.5G — 1G) may suffice. *But the Default out-of-the-box configuration value of 256M is most likely too low a value in most use-case scenarios.

*Remember that the WAS Java process shares a 4 Gigabyte memory address space with the OS in accordance with 32 bit design specification (User Virtual Memory is 2G).

Application Server       1024M — 1536M                 

Deployment Manager    512M — 1024M

Node Agent                    512M — 1024M

For 64 bit platforms and Java stacks in general, the recommended Maximum Heap range for WebSphere Application Server, would be between (4096M — 8192M) or (4G — 8G). For Node Agents and Deployment Manager, depending upon how many nodes are managed serviced and how many application deployments occur, you can probably utilize less heap memory, between (2048M — 4096M) or (2G — 4G).

*Remember that the WAS Java process shares a 16 Terabyte memory address space with the OS in accordance with 64 bit design specification (User Virtual Memory is 8T).

Application Server       4096M — 8192M                 

Deployment Manager  2048M — 4096M

Node Agent                  2048M — 4096M

Now regarding the Minimum Heap value, we have found that when using the newer product versions WAS v8.x and v9.x with default GC Policy of GENCON, setting a ‘Fixed Heap’ works and performs best (Maximum Heap Size = Minimum Heap Size) as well as a ‘Fixed Nursery’. You can fix the nursery size with a Generic JVM argument of -Xmn####m (example: -Xmn1024m for a 1Gb nursery region). Without -Xmn, the nursery region defaults to approximately 25% of the max heap size, but it is Variable and not Fixed. The concept of the GENCON GC Policy resizing heap regions was to keep them smaller for faster GC Cycles, but we have found out that in practice the overhead of this resizing often makes GC very inefficient. To navigate to the right area to set -Xmn, see «Setting generic JVM arguments in WebSphere Application Server.»

The Heap values can be set any number of ways depending upon the actual product version of WebSphere, but typically from the Admin Console JVM process settings, from the Generic JVM Args (-Xmx -Xms), WSAdmin command-line interface, Startup and Deployment scripts, manual server.xml modification (not recommended) and so forth; more details and step-by-step instructions can be found in the corresponding WebSphere product documentation based upon product version, as well as related developWorks articles and Blog entries.

*Please also keep in mind that the overall WAS JVM Process Size or Memory Footprint will typically be larger than Maximum Heap size (upwards of 1.5x), simply because it includes not only the Java Heap, but also underlying Classes and Jars, Threads and Stacks, Monitors, generated JIT code, malloc’d JNI Native Memory calls and so forth. For example:

  • -Xmx4G (process size could be around 6G on a busy AppServer)
  • -Xmx8G (process size could be around 12G on a busy AppServer)

Caveat: This blog entry was primarily created for WebSphere Base and Network Deployment full version products, but I wanted to also quickly point out that when using some of our stack products such as Business Process Monitor (BPM), eXtreme Scale, Portal, Process Server, the Maximum Heap sizes or ranges may need to be a bit larger than what I specified above.

Object Sizes in Memory Snapshots: Shallow and Retained Sizes

All individual objects, as well as sets of objects have their shallow and retained sizes.

Shallow size of an object is the amount of allocated memory to store the object itself,
not taking into account the referenced objects. Shallow size of a regular (non-array) object depends on
the number and types of its fields. Shallow size of an array depends on the array length and the type of
its elements (objects, primitive types). Shallow size of a set of objects represents the sum of shallow sizes
of all objects in the set.

Retained size of an object is its shallow size plus the shallow sizes of the objects that are accessible,
directly or indirectly, only from this object. In other words, the retained size represents the amount of
memory that will be freed by the garbage collector when this object is collected. In general,
retained size is an integral measure, which helps to understand the structure (clustering) of
memory and the dependencies between object subgraphs, as well as find potential roots of those subgraphs.

Dead objects are shown only with shallow size, as they do not actually retain any other objects.

Read more about shallow and retained sizes.

  • Content

PriorityQueue

The last collection to discuss is a . This collection is used in scenarios when from time to time you need to extract/get the smallest (or the largest, depending on your settings) element in the collection as well as to add the new elements to the collection. Extraction and insertion are mixed without any particular order.

is based on the binary heap, which is essentially an array, where children of entry with index N are located at and . The size of this array is increased twofold on each resize, so for sufficiently large collections we use between 50 and 100% of entries in the array. There are no wrappers for collection elements, which means that consumption is between 4 * SIZE and 8 * SIZE bytes (identical to despite their different purposes). We can also specify this size as 4 * CAPACITY bytes.

j stat

В дополнение к jcmd мы можем использовать jstat | для получения той же информации из запущенных приложений. Например, мы можем использовать jstat-gc для просмотра статистики кучи:

$ jstat -gc 4309
S0C    S1C    S0U    S1U      EC       EU        OC         OU       MC     
0.0    0.0    0.0    0.0   129024.0  5120.0   75776.0    10134.6   20864.0
MU      CCSC   CCSU     YGC     YGCT    FGC    FGCT     CGC    CGCT     GCTGCT
19946.2 2688.0 2355.0    2      0.007    1      0.020    0     0.000     0.027

Каждый столбец представляет объем памяти или использование определенной области памяти:

  • S0C — Емкость для первого выжившего пространства
  • S1C — Емкость для второго выжившего пространства
  • S0U — Используемое пространство первого выжившего
  • S1U — Используемое пространство второго выжившего
  • Космическая емкость EC — Eden
  • ЕС — Используемое пространство из Эдема
  • OC — Мощность старой генерации
  • OU — Используемое пространство от Старого поколения
  • Емкость MC — Metaspace
  • MU — Используемое пространство из Метапространства
  • CCSC — Объем пространства сжатого класса
  • CCSU — Используемое пространство для сжатых классов
  • YGC — Количество второстепенных GCS
  • YGCT — Время, затраченное на незначительные GCS
  • FGC — Количество полных ГКС
  • FGCT — Время, затраченное на полный GCs
  • CGC — Количество одновременных GCS
  • CGCT — Время, затраченное на параллельные GCS
  • GCT — Время, затраченное на все GCS

Существуют и другие параметры, связанные с памятью для jstat , такие как:

  • -gccapacity для сообщения о различных емкостях для различных областей памяти
  • Параметр -gcutil показывает только процент использования каждого региона
  • -gccause совпадает с -gcutil , но добавляет причину последних событий GC и, возможно, текущих событий GC

Обзор памяти Java

Краткий обзор структуры памяти Java:

1. Java Heap SizeМесто для хранения объектов, созданных приложением Java, это где Garbage Collection берет память для приложений Java. Для «тяжелого процесса Java», недостаточный размер кучи вызовет популярную ошибку: java.lang.OutOfMemoryError: Java heap space.

-Xms — Установить начальный размер Java куча «Java heap size»-Xmx — Установить максимальный размер Java куча «Java heap size»

2. Размер Perm Gen (Perm Gen Size).Место для хранения определение загруженного класса и метаданных. Если большой кодовый, базовый проект загружен, имеет недостаточный размер Perm Gen size то это вызовит ошибку: Java.Lang.OutOfMemoryError: PermGen.

-XX:PermSize — Установить начальный размер для параметра «PermGen Size».-XX:MaxPermSize — Установить максимальный размер для параметра «PermGen Size».

3. Размер java стека «Java Stack Size»Размер java нитей (Size of a Java thread). Если проект имеет много обработки нитей, попробуйте уменьшить этот размер стека, чтобы избежать нехватки памяти.

-Xss = Установить  размер стека Java (java thread stack size).

ЗАМЕТКА Значение по умолчанию для heap size, perm gen, или stack size отличаются от различных JVM. Лучшие практически всегда определить собственные значение для сервера.

More Java memory-related command line arguments

You can find more options for controlling Java application memory use by looking at the output of the command. Here’s what the output of those commands looks like from my JVM:

$ java -X

-Xmixed           mixed mode execution (default)
-Xint             interpreted mode execution only
-Xbootclasspath:  set search path for bootstrap classes and resources -Xbootclasspath/a:                   append to end of bootstrap class path -Xbootclasspath/p:                   prepend in front of bootstrap class path -Xnoclassgc       disable class garbage collection -Xloggc:    log GC status to a file with time stamps
-Xbatch           disable background compilation
-Xms              set initial Java heap size
-Xmx              set maximum Java heap size
-Xss              set java thread stack size
-Xprof            output cpu profiling data
-Xfuture          enable strictest checks, anticipating future default
-Xrs              reduce use of OS signals by Java/VM (see documentation)
-Xdock:name=      override default application name displayed in dock -Xdock:icon=                   override default icon displayed in dock -Xcheck:jni       perform additional checks for JNI functions -Xshare:off	      do not attempt to use shared class data -Xshare:auto      use shared class data if possible (default) -Xshare:on	      require using shared class data, otherwise fail.  The -X options are non-standard and subject to change without notice. 

From that list, the command-line arguments specifically related to Java application memory use are:

-Xnoclassgc   disable class garbage collection
-Xms          set initial Java heap size
-Xmx          set maximum Java heap size
-Xss          set java thread stack size

Рекомендации

  1. Oracle Memory Management Технический документ
  2. Oracle представляет постоянное поколение
  3. Эргономика в виртуальной машине Java 5.0
  4. Структура памяти JVM
  5. Heroku: проблемы с памятью Java
  6. StackOverflow: что такое «PermSize» в Java?
  7. StackOverflow: java.lang.OutOfMemoryError: пространство PermGen
  8. Объяснение java.lang.OutOfMemoryError: пространство PermGen
  9. JBoss OutOfMemoryExceptions
  10. Параметры Java HotSpot VM
  11. -XX: + PrintFlagsFinal
  12. Полезные флаги JVM — часть 3 (печать всех флагов XX и их значений)
  13. Проверка параметров JSM в HotSpot
  14. OpenJDK — глобальный исходный код

Размер кучи завивка поколения

Узнайте свой объем памяти кучи Java

0.00 (0%) votes

Java Heap Sizing Basics

Per default the JVM automatically configures heap size according to the spec of the machine it is running on. On my brand new MacBook Pro 2018 this yields the following heap size:

$ java -XX:+PrintFlagsFinal -version | grep -Ei "maxheapsize|maxram"    uintx DefaultMaxRAMFraction   = 4             {product}    uintx MaxHeapSize             := 8589934592   {product}    uint64_t MaxRAM               = 137438953472  {pd product}    uintx MaxRAMFraction          = 4             {product}

As you can see, the JVM defaults to 8.0 GB max heap and 0.5 GB initial heap on my machine. The formula behind this is straight forward. Using the JVM configuration parameter names, we end up with: where MaxRAM is the available RAM ) and MaxRAMFraction is 4 ) by default. That means the JVM allocates up to 25% of your RAM per JVM running on your machine.

It’s important to note that the JVM uses more memory than just heap. We can calculate the total memory usage roughly with . The default for XSS depends on the OS and JVM and is somewhere between 256 KB and 1 MB ). That means: every thread allocates at least 256 KB additional memory. The constant overhead is all memory allocated by the JVM which is not heap or stack. This value depends on a lot of factors. See ) and ) for more details.

You can change how the JVM does its memory management. The most common thing is to set MaxHeap () to a fixed, more or less carefully guessed value.

$ java -XX:+PrintFlagsFinal -Xmx1g -version | grep -Ei "maxheapsize|maxram"    uintx DefaultMaxRAMFraction   = 4            {product}    uintx MaxHeapSize             := 1073741824  {product}    uint64_t MaxRAM               = 137438953472 {pd product}    uintx MaxRAMFraction          = 4            {product}

There are other ways to control the heap, too. We can adjust , effectively simulating a smaller machine.

$ java -XX:+PrintFlagsFinal -XX:MaxRAM=1g -version | grep -Ei "maxheapsize|maxram"    uintx DefaultMaxRAMFraction   = 4            {product}    uintx MaxHeapSize             := 268435456   {product}    uint64_t MaxRAM               := 1073741824  {pd product}    uintx MaxRAMFraction          = 4            {product}

Now the JVM is back in charge calculating the heap size, we just fine tune the parameters. In this case we end up with 256 MB max heap. That’s fine for a desktop, but a bit conservative for a dedicated host. If we spend good money on a VPS with 1 GB RAM, we’d like the JVM to make better use of the available resources. Here comes into play. This parameter controls how much of the total RAM is up for grabs. yields the percentage of RAM we can use. Since it only allows integer values > 0, there are only a few sensible configurations.

+----------------+-------------------+| MaxRAMFraction | % of RAM for heap ||----------------+-------------------||              1 |              100% ||              2 |               50% ||              3 |               33% ||              4 |               25% |+----------------+-------------------+

So for our dedicated 1 GB server it’s enough to set and we end up 512 MB max RAM.

# -XX:MaxRAM is only set for the sake of this example to simulate a smaller physical machine$ java -XX:+PrintFlagsFinal -XX:MaxRAM=1g -XX:MaxRAMFraction=2 -version | grep -Ei "maxheapsize|maxram"    uintx DefaultMaxRAMFraction   = 4            {product}    uintx MaxHeapSize             := 536870912   {product}    uint64_t MaxRAM               := 1073741824  {pd product}    uintx MaxRAMFraction          := 2           {product}

That looks pretty good for prod!

Рейтинг
( Пока оценок нет )
Понравилась статья? Поделиться с друзьями:
Мой редактор ОС
Добавить комментарий

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: