Spring beans can be singleton or prototype. A bean definition defines a bean for Spring to manage including its class, id, and dependencies. Beans are created based on their dependencies with singletons created eagerly and prototypes created lazily. Bean properties are used to inject dependencies and can reference other beans. Beans without ids are anonymous while inner beans define dependencies inline. Init methods run after dependencies are loaded and values can be injected besides other beans. Abstract beans allow reusable bean definitions.
This document provides an introduction to Apache Hive, including what Hive is, its key features and architecture. Hive is a data warehouse infrastructure tool used to process structured data in Hadoop. It allows users to query and analyze large datasets using SQL-like queries. Hive resides on top of Hadoop and uses MapReduce to process queries internally. It includes a metastore to store metadata, query compiler and execution engine to process queries, and can operate on data stored in HDFS or HBase.
Java Hibernate Programming with Architecture Diagram and Examplekamal kotecha
Java Hibernate Introduction, Architecture and Example with step by step guidance to run the program especially for students and teachers.
Learn More @ http://java2all.com/technology/hibernate
The document provides information about strings in Java including:
1) Strings are objects in Java that are used to hold text data. The String class represents strings and provides various methods to work with strings.
2) There are two ways to create String objects: using string literals or the new keyword. String literals reuse existing objects in the string constant pool.
3) Important String class methods include charAt(), concat(), equalsIgnoreCase(), length(), replace(), substring(), toLowerCase(), toUpperCase(), and trim(). These methods allow manipulating and accessing string values.
Spring beans can be singleton or prototype. A bean definition defines a bean for Spring to manage including its class, id, and dependencies. Beans are created based on their dependencies with singletons created eagerly and prototypes created lazily. Bean properties are used to inject dependencies and can reference other beans. Beans without ids are anonymous while inner beans define dependencies inline. Init methods run after dependencies are loaded and values can be injected besides other beans. Abstract beans allow reusable bean definitions.
This document provides an introduction to Apache Hive, including what Hive is, its key features and architecture. Hive is a data warehouse infrastructure tool used to process structured data in Hadoop. It allows users to query and analyze large datasets using SQL-like queries. Hive resides on top of Hadoop and uses MapReduce to process queries internally. It includes a metastore to store metadata, query compiler and execution engine to process queries, and can operate on data stored in HDFS or HBase.
Java Hibernate Programming with Architecture Diagram and Examplekamal kotecha
Java Hibernate Introduction, Architecture and Example with step by step guidance to run the program especially for students and teachers.
Learn More @ http://java2all.com/technology/hibernate
The document provides information about strings in Java including:
1) Strings are objects in Java that are used to hold text data. The String class represents strings and provides various methods to work with strings.
2) There are two ways to create String objects: using string literals or the new keyword. String literals reuse existing objects in the string constant pool.
3) Important String class methods include charAt(), concat(), equalsIgnoreCase(), length(), replace(), substring(), toLowerCase(), toUpperCase(), and trim(). These methods allow manipulating and accessing string values.
Azul Systems. Are you interested in learning what a Java Virtual Machine (JVM) is and what it does for your Java applications? This presentation will provide insight into the inner workings of a Java Virtual Machine and some drill down on what compilers and garbage collectors do, so that you don't have to worry about it while programming your Java application. In particular, you will learn about common optimizations, well established garbage collection algorithms, and what the current biggest challenge with Java scalability is today.
In this Java Spring Training session, you will learn Spring – Inversion of Control, Dependency Injection and Bean definitions. Topics covered in this session are:
For more information, visit this link:
Spring Framework
• Core Container
• Data Access/Integration
• Web Layer
• Spring Setup
• Key features
• Spring Bean
• Dependency Injection
• Relation between DI and IoC
• Spring IoC Containers
• Spring DI
https://www.mindsmapped.com/courses/software-development/spring-fundamentals-learn-spring-framework-and-spring-boot/
Understanding REST APIs in 5 Simple StepsTessa Mero
This document summarizes the 5 steps to understanding REST APIs: 1) Understanding the purpose of APIs and their importance and growth, 2) Learning that REST defines functions to communicate via HTTP verbs and nouns, 3) Knowing that APIs use requests and responses, 4) Relying on documentation as the reference, and 5) Using debugging and testing tools to prevent issues. It provides examples of requests, responses, API documentation, and tools like Postman for working with REST APIs.
Garbage collection in .net (basic level)Larry Nung
This document provides an overview of garbage collection in .NET. It discusses the managed heap which stores objects and is divided into generations for younger and older objects. The large object heap stores larger objects separately. Garbage collection reclaims unused memory and objects are promoted between generations or finalized if they implement IDisposable. Collection can occur due to low memory or manually. Strong references protect objects while weak references allow collection. Garbage collection can run concurrently or in parallel depending on configuration.
The document discusses JavaScript scope, lexical scope, and hoisting. It defines three types of scope - global, local (function and block), and lexical scope. Lexical scope means that variable lookup follows the structure of nested functions and blocks. The document also explains that before code execution, variable and function declarations are stored in memory according to their scope due to a process called hoisting.
The document discusses various locators that can be used to locate elements in a web page using Selenium with Java, including ID, name, link text, CSS selector, DOM, and XPath. It provides examples and descriptions of how to use each locator type, such as using driver.findElement(By.id("username")) to locate an element by ID.
XML parsers are software libraries that allow client applications to work with XML documents. There are two main types: DOM parsers build an in-memory tree representation, while SAX parsers use event-based callbacks. Xerces-J is a popular Java XML parser that implements both DOM and SAX interfaces. An example extracts circle data from an XML file using both a DOM parser to iterate through nodes and a SAX parser overriding callback methods.
Profile your Java apps in production on Red Hat OpenShift with Cryostat | Dev...Red Hat Developers
Did you know that OpenJDK comes with Java Flight Recorder (JFR), an embedded production time profiler? Cryostat provides easy and secure access to JFR across container boundaries so you can profile that performance bottleneck, or find that annoying bug. Join this session to learn about using Cryostat to profile Java applications in production on OpenShift.
This document provides an overview of the Java Collections Framework. It discusses core collection interfaces like List, Set, and Map and their common implementations like ArrayList, HashSet, and HashMap. It also covers sorting collections with Comparable and Comparator, searching collections with binary search, and using utility methods in the Collections class. Examples are provided to illustrate usage of various collection classes and methods.
This document provides an overview of key concepts in the Java programming language, including:
- Java is an object-oriented language that is simpler than C++ and supports features like platform independence.
- The Java development environment includes tools for compiling, debugging, and running Java programs.
- Java programs work with basic data types like int and double, as well as user-defined classes, variables, and arrays.
- The document explains operators, control structures, formatting output, and the basics of classes and objects in Java.
This document provides an overview of Java applets, including:
- Java programs are divided into applications and applets, with applets running across the internet to make web pages dynamic.
- Applets override lifecycle methods like init(), start(), stop(), and destroy() and are run by web browsers with Java plugins.
- Creation of applets involves extending the Applet class, overriding methods, compiling, and embedding in an HTML file.
- Pros of applets include faster response time and security, while a con is requiring browser plugins.
- A sample applet draws a string using the paint() method, and this can be run from an HTML file or the applet viewer tool.
The document summarizes various collection classes in Java, including Collection, List, Set, and Map interfaces and their common implementations like ArrayList, LinkedList, HashSet, TreeSet, HashMap, and TreeMap. It discusses the pros and cons of different collection classes and how to iterate through collections using iterators to avoid ConcurrentModificationExceptions.
Room provides an abstraction layer over SQLite to allow fluent database access. It defines 3 main components - Entity, DAO, and Database. Entities represent tables, DAOs contain database access methods, and Database manages connections. Room avoids errors by verifying queries at compile time. Queries can return LiveData, Flowable, or RxJava observables to asynchronously retrieve data. Relationships between entities can be defined to retrieve related data.
Java 8 introduced several new features including default and static methods in interfaces, lambda expressions, the Optional class, streams, method references, a new date/time API, the Nashorn JavaScript engine, and parallel arrays. Some of the key features are default methods that allow interfaces to provide default implementations, lambda expressions that allow passing code as data, and streams that enable functional-style programming for collections.
This document discusses Java string classes and their differences. It provides an overview of strings in Java and describes the String, StringBuffer, and StringBuilder classes. The String class represents immutable strings and stores strings in a constant pool for efficiency. The StringBuffer and StringBuilder classes represent mutable strings but StringBuffer is synchronized for thread-safety while StringBuilder is not.
The document discusses the Java Collection Framework which provides interfaces and classes for storing and manipulating groups of objects, including Collection interfaces like List and Set, implementation classes like ArrayList, LinkedList, HashSet and TreeSet, and describes their features and usage.
The document discusses Java garbage collection. It explains that Java's garbage collector automatically manages memory by freeing unreferenced objects. The garbage collector runs when memory is low to find and delete objects that cannot be reached. While garbage collection provides convenience, it has overhead as the system must pause current execution to run it which can influence user experience. The document also describes how objects are identified as garbage using tracing and reference counting collectors as well as how to explicitly make objects available for collection and finalize objects before deletion.
HashMap is a part of Java's collection.. It provides the basic implementation of Map interface of Java. It stores the data in (Key, Value) pairs. To access a value key should be known. This ppt dives deep into the internal working of Hashmaps.
Azul Systems. Are you interested in learning what a Java Virtual Machine (JVM) is and what it does for your Java applications? This presentation will provide insight into the inner workings of a Java Virtual Machine and some drill down on what compilers and garbage collectors do, so that you don't have to worry about it while programming your Java application. In particular, you will learn about common optimizations, well established garbage collection algorithms, and what the current biggest challenge with Java scalability is today.
In this Java Spring Training session, you will learn Spring – Inversion of Control, Dependency Injection and Bean definitions. Topics covered in this session are:
For more information, visit this link:
Spring Framework
• Core Container
• Data Access/Integration
• Web Layer
• Spring Setup
• Key features
• Spring Bean
• Dependency Injection
• Relation between DI and IoC
• Spring IoC Containers
• Spring DI
https://www.mindsmapped.com/courses/software-development/spring-fundamentals-learn-spring-framework-and-spring-boot/
Understanding REST APIs in 5 Simple StepsTessa Mero
This document summarizes the 5 steps to understanding REST APIs: 1) Understanding the purpose of APIs and their importance and growth, 2) Learning that REST defines functions to communicate via HTTP verbs and nouns, 3) Knowing that APIs use requests and responses, 4) Relying on documentation as the reference, and 5) Using debugging and testing tools to prevent issues. It provides examples of requests, responses, API documentation, and tools like Postman for working with REST APIs.
Garbage collection in .net (basic level)Larry Nung
This document provides an overview of garbage collection in .NET. It discusses the managed heap which stores objects and is divided into generations for younger and older objects. The large object heap stores larger objects separately. Garbage collection reclaims unused memory and objects are promoted between generations or finalized if they implement IDisposable. Collection can occur due to low memory or manually. Strong references protect objects while weak references allow collection. Garbage collection can run concurrently or in parallel depending on configuration.
The document discusses JavaScript scope, lexical scope, and hoisting. It defines three types of scope - global, local (function and block), and lexical scope. Lexical scope means that variable lookup follows the structure of nested functions and blocks. The document also explains that before code execution, variable and function declarations are stored in memory according to their scope due to a process called hoisting.
The document discusses various locators that can be used to locate elements in a web page using Selenium with Java, including ID, name, link text, CSS selector, DOM, and XPath. It provides examples and descriptions of how to use each locator type, such as using driver.findElement(By.id("username")) to locate an element by ID.
XML parsers are software libraries that allow client applications to work with XML documents. There are two main types: DOM parsers build an in-memory tree representation, while SAX parsers use event-based callbacks. Xerces-J is a popular Java XML parser that implements both DOM and SAX interfaces. An example extracts circle data from an XML file using both a DOM parser to iterate through nodes and a SAX parser overriding callback methods.
Profile your Java apps in production on Red Hat OpenShift with Cryostat | Dev...Red Hat Developers
Did you know that OpenJDK comes with Java Flight Recorder (JFR), an embedded production time profiler? Cryostat provides easy and secure access to JFR across container boundaries so you can profile that performance bottleneck, or find that annoying bug. Join this session to learn about using Cryostat to profile Java applications in production on OpenShift.
This document provides an overview of the Java Collections Framework. It discusses core collection interfaces like List, Set, and Map and their common implementations like ArrayList, HashSet, and HashMap. It also covers sorting collections with Comparable and Comparator, searching collections with binary search, and using utility methods in the Collections class. Examples are provided to illustrate usage of various collection classes and methods.
This document provides an overview of key concepts in the Java programming language, including:
- Java is an object-oriented language that is simpler than C++ and supports features like platform independence.
- The Java development environment includes tools for compiling, debugging, and running Java programs.
- Java programs work with basic data types like int and double, as well as user-defined classes, variables, and arrays.
- The document explains operators, control structures, formatting output, and the basics of classes and objects in Java.
This document provides an overview of Java applets, including:
- Java programs are divided into applications and applets, with applets running across the internet to make web pages dynamic.
- Applets override lifecycle methods like init(), start(), stop(), and destroy() and are run by web browsers with Java plugins.
- Creation of applets involves extending the Applet class, overriding methods, compiling, and embedding in an HTML file.
- Pros of applets include faster response time and security, while a con is requiring browser plugins.
- A sample applet draws a string using the paint() method, and this can be run from an HTML file or the applet viewer tool.
The document summarizes various collection classes in Java, including Collection, List, Set, and Map interfaces and their common implementations like ArrayList, LinkedList, HashSet, TreeSet, HashMap, and TreeMap. It discusses the pros and cons of different collection classes and how to iterate through collections using iterators to avoid ConcurrentModificationExceptions.
Room provides an abstraction layer over SQLite to allow fluent database access. It defines 3 main components - Entity, DAO, and Database. Entities represent tables, DAOs contain database access methods, and Database manages connections. Room avoids errors by verifying queries at compile time. Queries can return LiveData, Flowable, or RxJava observables to asynchronously retrieve data. Relationships between entities can be defined to retrieve related data.
Java 8 introduced several new features including default and static methods in interfaces, lambda expressions, the Optional class, streams, method references, a new date/time API, the Nashorn JavaScript engine, and parallel arrays. Some of the key features are default methods that allow interfaces to provide default implementations, lambda expressions that allow passing code as data, and streams that enable functional-style programming for collections.
This document discusses Java string classes and their differences. It provides an overview of strings in Java and describes the String, StringBuffer, and StringBuilder classes. The String class represents immutable strings and stores strings in a constant pool for efficiency. The StringBuffer and StringBuilder classes represent mutable strings but StringBuffer is synchronized for thread-safety while StringBuilder is not.
The document discusses the Java Collection Framework which provides interfaces and classes for storing and manipulating groups of objects, including Collection interfaces like List and Set, implementation classes like ArrayList, LinkedList, HashSet and TreeSet, and describes their features and usage.
The document discusses Java garbage collection. It explains that Java's garbage collector automatically manages memory by freeing unreferenced objects. The garbage collector runs when memory is low to find and delete objects that cannot be reached. While garbage collection provides convenience, it has overhead as the system must pause current execution to run it which can influence user experience. The document also describes how objects are identified as garbage using tracing and reference counting collectors as well as how to explicitly make objects available for collection and finalize objects before deletion.
HashMap is a part of Java's collection.. It provides the basic implementation of Map interface of Java. It stores the data in (Key, Value) pairs. To access a value key should be known. This ppt dives deep into the internal working of Hashmaps.
An Introduction to JVM Internals and Garbage Collection in JavaAbhishek Asthana
This document provides an overview of Java memory structures and garbage collection. It discusses the key areas of memory used by the JVM - heap, method area, native area, and threads. It then covers garbage collection concepts like roots, algorithms like mark-sweep-compact, and different GC strategies like serial, parallel, concurrent mark-sweep, and Garbage First collector. Performance metrics for evaluating GC and how objects transition between generations in generational collection are also summarized.
В презентации рассказывается о структурах памяти в JVM: Heap, Non-Heap, Stack, об атомарности операций и о garbage collector. Рассмотрен пример, как работает стек. Также, приведены примеры, как использовать jVisualVM и что она может показать.
There are hundreds of JVM parameters and options out there. Here we are going to take a closer look at the internal structure of HotSpot VM while over-viewing memory spaces and different types of Garbage Collectors.
Видеозапись:
http://getdev.net/Event/dependency-injection
Рассказ о внедрении зависимостей (Dependency Injection), зачем оно нужно, откуда оно пошло и развивалось. Виды Dependency Injection, разница между ними и рекомендации к применению. Расказ про декораторы (decorators). Рассказ про абстрактные фабрики. Рассказ про управление временем жизни. Рассказ про IoC -контейнеры вообще и Castle Windsor в частности.
Занятие №3 в рамках Курсов программирования Ruby on Rails.
Группа курсов «ВКонтакте»: http://vk.com/ruby_school
Организатор — Агентство интернет-маркетинга Мэйк makeagency.ru. Курсы проводятся на базе Кузбасского государственного технического университета, кафедры «Информационные и автоматизированные производственные системы».
3. Класс Object
Класс Object - это базовый класс
для всех остальных объектов.
В Java каждый класс неявно
наследуется от класса Object.
Соответственно все классы наследуют
методы класса Object.
4. Метод equals
public boolean equals(Object obj) -
служит для сравнения объектов по
значению, а не по ссылке.
Сравнивается состояние объекта, у
которого вызывается этот метод, с
передаваемым аргументом.
public boolean equals(Object object) {
return (this == object);
}
5. Методы класса Object
public String toString() - Этот метод
позволяет получить текстовое описание
любого объекта. Создавая новый класс,
данный метод можно переопределить и
возвращать более подробное описание.
return getClass().getName() + "@" +
Integer.toHexString(hashCode());
6. Методы класса Object
public final native Class getClass()
-Этот метод возвращает объект класса
Class, который описывает класс(имя,
методы, поля), от которого был
порожден этот объект.
public native int hashCode() - данный
метод возвращает значение int. Цель
hashCode() – представить любой объект
целым числом.
7. Метод clone
protected native Object clone() throws
CloneNotSupportedException-
При выполнении метода clone()сначала
проверяется, можно ли клонировать
исходный объект. Если разработчик
хочет сделать объекты своего класса
доступными для клонирования через
Object.clone(), то он должен
реализовать в своем классе интерфейс
Cloneable.
8. Методы класса Object
Методы wait(), notify(), notifyAll()
используются для поддержки
многопоточности.
protected void finalize() throws
Throwable - данный метод вызывается
при уничтожении объекта
автоматическим сборщиком мусора
(garbage collector).
9. Анатомия объекта Java
Когда Java-код использует оператор
new для создания экземпляра объекта
Java, выделяется намного больше
данных, чем следовало бы ожидать.
10. Анатомия объекта Java
Например, соотношение размеров
между значением типа int и объектом
Integer— самым малым объектом,
который может содержать значение int,
— обычно составляет 1:4.
Накладные расходы приходятся на
метаданные, которые JVM использует для
описания объекта Java, в данном случае
Integer.
11. Метаданные
Class: указатель на сведения о классе, который
описывает тип объекта. В случае объекта
java.lang.Integer, например, это указатель на класс
java.lang.Integer;
флаги: набор флагов, которые описывают
состояние объекта, включая хэш-код для объекта,
если он есть, и форму объекта (то есть является
ли объект массивом);
Lock: сведения о синхронизации объекта — то
есть синхронизирован ли объект в настоящее
время.
12. Данные объекта
За метаданными объекта следуют
собственно данные объекта, состоящие
из полей, хранящихся в экземпляре
объекта. В случае объекта
java.lang.Integer это одно значение типа
int.
15. Сборка муссора
В программировании сборка мусора
(устоявшийся термин, с точки зрения
русского языка правильнее «сбор
мусора», англ.
garbage collection, GC)
— одна из форм
автоматического
управления памятью.
16. Сборщик мусора
Специальный процесс, называемый
сборщиком мусора (англ. garbage
collector), периодически освобождает
память, удаляя объекты, которые уже
не будут востребованы приложениями.
17. Принцип работы GC
Существует множество
алгоритмов, которыми может
воспользоваться JVM для
проведения garbage collection.
Можно указать, какие из них
будут использоваться JVM с
помощью параметров.
18. Размер кучи
Начальный размер кучи — это соотношение 1/64
физической памяти к 1 Гб.
Максимальный размер кучи — это
соотношение 1/4 физической памяти до 1 Гб.
Тем не менее, алгоритмы выделения могут
варьироваться в разных VM.
19. Старые и молодые объекты
В динамической памяти приложения некоторые
объекты становятся мусором вскоре после
создания, некоторые живут в течение долгого
времени и только затем становятся мусором,
другие могут остаться в живых в течение всего
времени работы программы. Эмпирические
исследования показали, что в большинстве
объектно-ориентированных языков, включая
Java, огромное количество объектов,
приблизительно 98 % умирают молодыми.
20.
21. Деление кучи
Eden Space (heap): область, в которой
размещается большинство вновь
созданных объектов.
Survivor Space (heap): область, которая
содержит объекты, которые "выжили" после
очистки мусора в области Eden Space.
Tenured Generation (heap): содержит
объекты, которые существовали некоторое
время в Survivor Space.
25. Вне кучи
Permanent Generation (non-heap) –
Здесь хранится метаинформация,
используемая JVM (используемые
классы, методы и т.п.).
В частноси Code Cache (non-heap) —
эта область используется JVM, когда
включена JIT-компиляция, в ней
кешируется скомпилированный
платформенно — зависимый код.
26. Разница между Stack и Heap памятью в
Java
Куча используется всеми
частями приложения в то время
как стек используется только
одним потоком исполнения
программы.
27. Разница между Stack и Heap памятью в
Java
Всякий раз, когда создаётся объект,
он всегда хранится в куче, а в
памяти стека содержится ссылка на
него. Память стека содержит
только локальные переменные
примитивных типов и ссылки на
объекты в куче.
28. Разница между Stack и Heap памятью в
Java
Объекты в куче доступны с
любой точки программы, в то
время как стековая память
доступна только для одного
потока.
29. Разница между Stack и Heap памятью в
Java
Стековая память существует
лишь какое-то время работы
программы, а память в куче
живёт с самого начала до
конца работы программы.
30. Разница между Stack и Heap памятью в
Java
Размер памяти стека намного меньше
памяти в куче. Из-за простоты
распределения памяти (LIFO), стековая
память работает намного быстрее кучи.
31. java.lang.OutOfMemoryError:
Java heap space
Не хватает место в куче, а именно, в
области памяти в которую помещаются
объекты, создаваемые программно в
вашем приложении. Размер задаётся
параметрами -Xms и -Xmx. Если вы
пытаетесь создать объект, а места в
куче не осталось, то получаете эту
ошибку.
32. java.lang.OutOfMemoryError:
PermGen space
Данная ошибка возникает при нехватке
места в Permanent области, размер
которой задается параметрами
-XX:PermSize и -XX:MaxPermSize.
Метаданные об объектах
С точки зрения java в этой области лежат
те же объекты, что и в основной куче.
Только это объекты определенных типов,
а именно Class, Method, Field и Constructor.
33. java.lang.OutOfMemoryError: GC
overhead limit exceeded
Данная ошибка может возникнуть как
при переполнении первой, так и второй
областей. Связана она с тем, что
памяти осталось мало и GC постоянно
работает, пытаясь высвободить
немного места. Данную ошибку можно
отключить с помощью параметра -XX:-
UseGCOverheadLimit
34. java.lang.OutOfMemoryError: unable to
create new native thread
Допустим у вас есть приложение с большим
количеством одновременно работающих
пользователей, которое запускается с
параметрами -Xmx1024M
-XX:MaxPermSize=256M -Xss512K. Если всего
процессу доступно 2G, то остаётся
свободным ещё около 768M. Именно в
данном остатке памяти и создаются стеки
потоков. Таким образом, примерно вы можете
создать не больше 768*(1024/512)=1536.
35. Размещение в памяти
При создании объекта, когда вы пишете
что-то типа byte[] data = new byte[1024],
этот объект создаётся в сегменте Eden.
Новые объекты всегда размешаются в
Eden. Когда вы хотите создать новый
объект, но места в Eden уже нет, JVM
проводит сборку муссора (JVM ищет в
памяти все объекты, которые более не
нужны, и избавляется от них).
36. Стратегии сборки мусора
Как только определено множество
недостижимых объектов, сборщик
мусора может освободить память,
занимаемую ими, и оставить все
остальное как есть.
37. Стратегии сборки мусора
Также можно после освобождения
памяти переместить все или часть
оставшихся объектов в другие области
памяти, обновив вместе с этим все
ссылки на них. Эти два варианта
реализации называются,
соответственно, не перемещающим и
перемещающим.
38. Copy Collection
На первом этапе Mark помечаются
неиспользуемые объекты (красные).
На втором (Copy) объекты, которые ещё
нужны (d) копируется в сегмент survivor
– квадрат справа.
Сегментов Survivor два,
и они меньше Eden.
39. Copy Collection
Теперь все объекты, которые мы хотим,
чтобы они были сохранены,
скопированы в Survivor, и JVM просто
удаляет всё из Eden. На этом всё. Этот
алгоритм создаёт кое-что, что
называется моментом,
«когда мир остановился».
40. Mark and Sweep
Объекты распределяются в памяти
Нужно запустить GC
Приложение приостанавливается
Сборщик проходится по дереву объектов,
помечая живые объекты
Сборщик проходится по всей памяти, находя все
не отмеченные куски памяти, сохраняя их в "free list"
Когда новые объекты начинают распределятся
они распределяются в память доступную в "free list"
42. Mark-Sweep-Compact Collection
1. Mark»: помечаются неиспользуемые объекты
(красные).
2. «Sweep»: эти объекты удаляются из памяти.
Обратите внимание на пустые слоты на
диаграмме.
3. «Compact»: объекты
размещаются, занимая
свободные слоты,
что освобождает пространство
на тот случай, если потребуется
создать «большой» объект.
43. Алгоритм подсчёта ссылок
Использование алгоритма замедляет
операции присваивания ссылок, но зато
определение достижимых объектов
тривиально — это все объекты, значение
счётчика ссылок которых превышает нуль.
Без дополнительных уточнений этот
алгоритм, в отличие от предыдущего, не
удаляет циклически замкнутые цепочки
вышедших из употребления объектов,
сохранивших ссылки друг на друга.
44. Финализаторы
Финализатор указывает, что делать, когда
объект попадает под сборщик мусора.
Финализатор — это метод класса, который
автоматически вызывается средой
исполнения в промежутке времени между
моментом, когда объект этого класса
опознаётся сборщиком мусора как
неиспользуемый, и моментом удаления
объекта (освобождения занимаемой им
памяти).
45. Финализаторы
Финализатор для конкретного
объекта всегда выполняется после
того, как программа прекращает
использовать данный объект и до
того, как занимаемая объектом
память будет освобождена
сборщиком мусора.
48. Пакет JDK содержит и многочисленные
возможности для настройки сборки мусора.
Вы можете провести значительное время,
настраивая эти опции и оценивая эффект,
поэтому до того как Вы попытаетесь
настроить сборщик мусора, тщательно
убедитесь, что Ваше приложение хорошо
оптимизировано и выстроено.
Настройка GC