- What is garbage collection?
- When is the method called
finalize
? - What happens if
finalize
an exception occurs in a method? - What's happened
SoftReference
? - What's happened
WeakReference
? - What's happened
PhantomReference
? - How does it work
WeakHashMap
? Where is it used? - Why do you need to pass a queue to the constructor
PhantomReference
? - Why do you need a logger?
- What logger settings do you know?
-
This is a mechanism for destroying unnecessary objects. Unneeded objects are unused objects. There are two ways to find such objects: reference counting and tracing. In the first case, each object is associated with a variable that stores the number of references to this object. If this number drops to zero, then the object is considered dead. In the second case, the garbage collector follows object references from root points to the end (until the null value), traversing this entire tree. Objects that it cannot reach from the root points are considered dead. The root points are all active threads, the main method, the arguments of the method
main()
, as well as all static variables of the class in which the method is locatedmain()
.Determining which objects are eligible for destruction is only the first part of the garbage collector's job. The second part is actually deleting them and working with memory. A hybrid approach is used here. All memory available for objects is divided into three areas: the area of young objects, the area of old objects and the area of permanent objects (these are classes, metadata, interned strings, etc.). The first area is divided into three more subareas: Eden and suvivor space 1 and 2. Eden stores all newly created objects. The remaining two zones store objects that survive the last garbage collection. The garbage collector works with this entire area (the area of young objects) as follows. During the next garbage collection, he finds living objects in the Eden area and copies them to the second survivor area. After this, he also looks for living objects in the first area and copies them either to the second area of survivors, or, if they are already “old” enough, to the area of the old generation. Afterwards, he clears the Eden area and the first survivor area. Next, he considers the second area of survivors to be the first. And that’s it, garbage collection ends for this area.
Для второй области сборка мусора идёт несколько по-другому. Там есть одна большая область, она ни на что не делится, но сборщик мусора все живые an objectы в ней во время своей работы перемещает в начало области. Соответственно, вторая часть области будет состоять только из пустого пространства и мёртвых an objectов. После этого сборщик мусора завершает свою работу.
-
Перед уничтожение an object сборщиком мусора. Также можно вручную запустить вызовы этого метода у всех недостижимых an objectов, для этого надо вызвать метод
System.runFinalization()
orRuntime.getRuntime().runFinalization()
. -
Это исключение будет проигнорировано, и произойдёт выход из метода.
-
SoftReference
переводится How "мягкая link". Эта link на an object, но более слабая, чем обычная link (StrongReference). Объекты, на которые сущесвуют только мягкие ссылки, называются мягcodeостижимыми. Такие an objectы не уничтожаются в обычном случае. Но если у JVM закочиналась память, то сборщик мусоры удаляет все такие an objectы. -
WeakReference
— это так называемая слабая link на an object. Она ещё слабее Soft-ссылки. Все an objectы, на которые существуют только слабые ссылки, будут удалены при ближайщей сборке мусора. -
PhantomReference
— это самая слабая link. Механизм работы с такими link запускается только если на an object нет больше ниHowих других ссылок. Призрачные ссылки используются для сложной proceduresы удаления an object. Это может быть необходимо, если an object делает что за граница Java-машины, например, вызывает низкоуровневые функции ОС or пишет своё состояние в файл, or делает ещё что-то важное и сложное.Механизм работы с такими linkми следующий. Если на an object не осталось больше ниHowих других ссылок, и у него переопределён метода
finalize()
, то этот метода будет вызван во время ближащей сборки мусора. Если же этот метод не переопределён, то этот an object пропускает текущую сборку мусора, и попадает только в следующую. Во время этой (следующей) сборки мусора данный an object помещается в очередь призрачных an objectов, из которой будет удалён, когда у его призрачной ссылки вызовут методclear()
. Также стоит отметить, что методаget()
у призрачной link всегда возвращает null (в отличие от двух других несильных ссылок, у которых он возвращаетnull
, только если an object уже уничтожен). -
WeakHashMap
— этоHashMap
, у которого ключами являются слабые ссылки. Поэтому, если во время ближайшей сборки мусора будет обнаружено, что на an object существует только link вWeakHashMap
, то изWeakHashMap
будет удалена вся пара "ключ-meaning", связанная с этим an objectом.В связи с этим данная коллекция может быть использована для хранения Howой-то дополнительной, не очень важной информации об an objectе. Также её удобно использоваться для хранения Howой-то временной информации (которая нужная только в рамках данной операции).
-
Эта очередь используется для отслеживания того, что an object больше не нужен. Может быть использовано для закрытия ресурсов, открытых данным an objectом (например, удаление созданных файлов).
-
A logger is needed to save information about the behavior of the program, as well as some of its states. Can be used for debugging and identifying program errors and failures. The logger also allows the developer to receive feedback from his program while it is running. In addition, in case of critical failures, the logger can quickly notify the right people (for example, developers, clients, project managers, technical support, etc.) about these failures.
-
When setting up logging, you can specify the following things:
- the place where the information will be written (file, console, database, network, etc.)
- what level messages will be recorded
- type of log entries
- for files you can specify: path to file and directory, file size, number of files
- specify for each individual package its own level of messages that will be written to the log
GO TO FULL VERSION