Garbage collector java какие бывают

Garbage collector java какие бывают

The discussion to this point has been about the serial collector. The Java HotSpot VM includes three different types of collectors, each with different performance characteristics.

Serial Collector

The serial collector uses a single thread to perform all garbage collection work, which makes it relatively efficient because there is no communication overhead between threads.

It’s best-suited to single processor machines because it can’t take advantage of multiprocessor hardware, although it can be useful on multiprocessors for applications with small data sets (up to approximately 100 MB). The serial collector is selected by default on certain hardware and operating system configurations, or can be explicitly enabled with the option -XX:+UseSerialGC .

Parallel Collector

The parallel collector is also known as throughput collector , it’s a generational collector similar to the serial collector. The primary difference between the serial and parallel collectors is that the parallel collector has multiple threads that are used to speed up garbage collection.

The parallel collector is intended for applications with medium-sized to large-sized data sets that are run on multiprocessor or multithreaded hardware. You can enable it by using the -XX:+UseParallelGC option.

Parallel compaction is a feature that enables the parallel collector to perform major collections in parallel. Without parallel compaction, major collections are performed using a single thread, which can significantly limit scalability. Parallel compaction is enabled by default if the option -XX:+UseParallelGC has been specified. You can disable it by using the -XX:-UseParallelOldGC option.

Читайте также:  Java stream count words

Garbage-First (G1) Garbage Collector

G1 is a mostly concurrent collector. Mostly concurrent collectors perform some expensive work concurrently to the application. This collector is designed to scale from small machines to large multiprocessor machines with a large amount of memory. It provides the capability to meet a pause-time goal with high probability, while achieving high throughput.

G1 is selected by default on most hardware and operating system configurations, or can be explicitly enabled using -XX:+UseG1GC .

The Z Garbage Collector

The Z Garbage Collector (ZGC) is a scalable low latency garbage collector. ZGC performs all expensive work concurrently, without stopping the execution of application threads.

ZGC provides max pause times of a few milliseconds, but at the cost of some throughput. It is intended for applications, which require low latency. Pause times are independent of heap size that is being used. ZGC supports heap sizes from 8MB to 16TB. To enable this, use the -XX:+UseZGC option.

Selecting a Collector

Unless your application has rather strict pause-time requirements, first run your application and allow the VM to select a collector.

If necessary, adjust the heap size to improve performance. If the performance still doesn’t meet your goals, then use the following guidelines as a starting point for selecting a collector:

  • If the application has a small data set (up to approximately 100 MB), then select the serial collector with the option -XX:+UseSerialGC .
  • If the application will be run on a single processor and there are no pause-time requirements, then select the serial collector with the option -XX:+UseSerialGC .
  • If (a) peak application performance is the first priority and (b) there are no pause-time requirements or pauses of one second or longer are acceptable, then let the VM select the collector or select the parallel collector with -XX:+UseParallelGC .
  • If response time is more important than overall throughput and garbage collection pauses must be kept shorter, then select the mostly concurrent collector with -XX:+UseG1GC .
  • If response time is a high priority, then select a fully concurrent collector with -XX:UseZGC .

These guidelines provide only a starting point for selecting a collector because performance is dependent on the size of the heap, the amount of live data maintained by the application, and the number and speed of available processors.

If the recommended collector doesn’t achieve the desired performance, then first attempt to adjust the heap and generation sizes to meet the desired goals. If performance is still inadequate, then try a different collector: Use the concurrent collector to reduce pause-time, and use the parallel collector to increase overall throughput on multiprocessor hardware.

Источник

Сборка мусора в Java

В этой статье поговорим о сборке мусора (Garbage Collection) в java.

Память в JVM делится на три части:

  • Young generation (молодое поколение).
  • Old generation (старое поколение).
  • Metaspace (Perm Gen).

Young Generation (молодое поколение)

Как следует из названия, Young Generation — это область памяти для новых, вновь создаваемых объектов.

  • Когда область Young Generation заполняется, то запускается минорная сборка мусора (Minor GC).
  • При Minor GC «мертвые» объекты удаляются из Young Generation.
  • Чем больше «мертвых» объектов в Young Generation, тем быстрее выполняется Minor GC.
  • При Minor GC происходит «остановка мира» (stop the world) — все потоки в приложении останавливаются.

Давайте подробнее разберемся со структурой Young generation.

Young generation разделен на три части: Eden, S0, S1.

  • Все новые объекты размещаются в Eden Space.
  • При заполнении Еden space происходит minor GC: все «живые» объекты перемещаются в одно из пространств уцелевших объектов (survivor space): S0 или S1. Допустим, в нашем случае, все объекты будут перемещены в S0.

Для дальнейшего эксперимента я написал и запустил программу, которая создает короткоживущие объекты.

Давайте посмотрим распределение памяти в Visual GC (плагин для VisualVM).

Как видно, в S0 совсем мало объектов, и как только Еden Space заполняется, все объекты, на которые есть ссылки, перемещаются в S1.

Old generation (старое поколение)

  • В Old generation располагаются долгоживущие объекты.
  • Как правило, эта область больше, чем область для young generation.
  • При заполнении (или достижении заданного порога) происходит Major GC.
  • Обычно Major GC выполняются медленнее и реже, чем minor GC.

Как с помощью этой информации можно оптимизировать использование памяти?

Все зависит от типа приложения.

Если у вас много временных объектов, то будет много Minor GC. В этом случае можно использовать параметр XX:NewRatio=1, чтобы распределить 50% на young generation и 50% на old generation.

По умолчанию NewRatio=2, т.е. young generation составляет 1/3 всей кучи (heap).

При множестве долгоживущих объектов можно сделать область старого поколения больше, увеличив NewRatio.

Зачем используется два survivor space?

Вы наверняка задумались над тем, почему используется два survivor space? Для борьбы с фрагментацией памяти. При каждом копировании объектов из eden в survivor, вы получаете пустой eden и один пустой survivor.

Алгоритмы сборки мусора

В JVM есть несколько сборщиков мусора с разными алгоритмами для молодого и старого поколения. Есть три типа алгоритмов.

Serial collector (последовательный сборщик)

Для сборки мусора используется один поток. Подходит для простых приложений с однопроцессорными машинами.

Parallel collector (параллельный сборщик)

В отличие от последовательного сборщика, использующего один поток, параллельный использует несколько потоков. Эффективен при достаточном объеме памяти и количестве процессорных ядер.

Concurrent collector (конкурентный сборщик)

Concurrent collector выполняет сборку мусора вместе с работой потоков вашего приложения. Эффективен для приложений, обрабатывающих средние и большие наборы данных и требующих малого времени отклика.

Для молодого и старого поколений можно использовать разные, но совместимые, алгоритмы GC. Например, нельзя использовать Parallel Scavenge для молодого поколения одновременно с Concurrent Mark Sweep для старого, так как Parallel Scavenge не обеспечивает синхронизацию, которая требуется в CMS.

После Java 8 в сборке мусора произошло много изменений, о которых я расскажу в других статьях.

Приглашаем всех желающих на demo-урок «Переопределение, скрытие, передекларация». На занятии рассмотрим переопределение и скрытие методов в Java, а также передекларация и скрытие переменных; познакомимся с четырьмя правилами, а потом ещё и с пятым. Регистрация доступна по ссылке.

Источник

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