JavaRush /Java Blog /Random EN /Level 34. Answers to interview questions on the level top...
lichMax
Level 40
Санкт-Петербург

Level 34. Answers to interview questions on the level topic

Published in the Random EN group
I searched the site using my native search and searched everything using Google - there are no answers to the questions from this level. Maybe I missed something, and they are still here somewhere on the site!? Level 34. Answers to interview questions on the topic of level - 1Just in case, I am attaching the answers that I wrote for myself: Questions for the interview:
  1. What is garbage collection?
  2. When is the method called finalize?
  3. What happens if finalizean exception occurs in a method?
  4. What's happened SoftReference?
  5. What's happened WeakReference?
  6. What's happened PhantomReference?
  7. How does it work WeakHashMap? Where is it used?
  8. Why do you need to pass a queue to the constructor PhantomReference?
  9. Why do you need a logger?
  10. What logger settings do you know?
My answers:
  1. 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 located main().

    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ов. После этого сборщик мусора завершает свою работу.

  2. Перед уничтожение an object сборщиком мусора. Также можно вручную запустить вызовы этого метода у всех недостижимых an objectов, для этого надо вызвать метод System.runFinalization() or Runtime.getRuntime().runFinalization().

  3. Это исключение будет проигнорировано, и произойдёт выход из метода.

  4. SoftReference переводится How "мягкая link". Эта link на an object, но более слабая, чем обычная link (StrongReference). Объекты, на которые сущесвуют только мягкие ссылки, называются мягcodeостижимыми. Такие an objectы не уничтожаются в обычном случае. Но если у JVM закочиналась память, то сборщик мусоры удаляет все такие an objectы.

  5. WeakReference — это так называемая слабая link на an object. Она ещё слабее Soft-ссылки. Все an objectы, на которые существуют только слабые ссылки, будут удалены при ближайщей сборке мусора.

  6. 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 уже уничтожен).

  7. WeakHashMap — это HashMap, у которого ключами являются слабые ссылки. Поэтому, если во время ближайшей сборки мусора будет обнаружено, что на an object существует только link в WeakHashMap, то из WeakHashMap будет удалена вся пара "ключ-meaning", связанная с этим an objectом.

    В связи с этим данная коллекция может быть использована для хранения Howой-то дополнительной, не очень важной информации об an objectе. Также её удобно использоваться для хранения Howой-то временной информации (которая нужная только в рамках данной операции).

  8. Эта очередь используется для отслеживания того, что an object больше не нужен. Может быть использовано для закрытия ресурсов, открытых данным an objectом (например, удаление созданных файлов).

  9. 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.

  10. 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
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION