Зачем нужен метод finalize в java
Перейти к содержимому

Зачем нужен метод finalize в java

  • автор:

Finalize Method in Java

In Java, finalize() method is defined in java.lang.Object class, which is called before garbage collection.

When an object is no longer referenced by other objects, it can be seen as garbage. Then JVM would collect it in some time. For example, suppose we have a Lion class:

Then we can design a case in which the Lion object Mufasa can be garbage collected:

Since Mufasa is no longer referenced, it would be garbage collected. Therefore, the output of the above code is:

Note that explicitly calling System.gc() is a bad practice. Here we just use this method to force the JVM to garbage collect Mufasa .

From the above discussion, we can know that the finalize() method can be implicitly called (by JVM) to reclaim memory resource. Besides, programers can also explicitly call this method to close other resources such as sockets and data streams. For example, we can close these resources in finalize() method:

Then we can explicitly call finalize() method in our code:

However, the finalize method is deprecated since Java 9. Instead, we can use try-with-resources statement to close our resources, i.e.,

Resources such as Socket and InputStream all implemented the Closable interface, and the Closable interface extended the Autoclosable interface, so that Java can close these resources automatically for us.

Использование Final, Finally и Finalize на Java

Если у вас есть какой-либо опыт интервью, вы могли заметить, что интервьюеры, как правило, задают сложные вопросы, которые обычно берутся из базовых понятий. Один из таких вопросов, который чаще всего задают, заключается в различении между Final, Finally and Finalize на Java.

Что такое Java final?

В Java final – это ключевое слово, которое также можно использовать в качестве модификатора доступа. Другими словами, final ключевое слово используется для ограничения доступа пользователя. Он может использоваться в различных контекстах, таких как:

  1. Переменная;
  2. Метод;
  3. Класс.

С каждым из них последнее ключевое слово имеет разный эффект.

1. Переменная

Всякий раз, когда ключевое слово final в Java используется с переменной, полем или параметром, это означает, что после передачи ссылки или создания экземпляра его значение не может быть изменено во время выполнения программы. Если переменная без какого-либо значения была объявлена как final, тогда она называется пустой / неинициализированной конечной переменной и может быть инициализирована только через конструктор.

Давайте теперь посмотрим на пример.

2. Метод

В Java всякий раз, когда метод объявляется как final, он не может быть переопределен никаким дочерним классом на протяжении всего выполнения программы.

Давайте посмотрим на пример.

3. Класс

Когда класс объявляется как final, он не может наследоваться ни одним подклассом. Это происходит потому, что, как только класс объявлен как final, все члены-данные и методы, содержащиеся в классе, будут неявно объявлены как final.

Кроме того, как только класс объявлен как final, он больше не может быть объявлен как абстрактный. Другими словами, класс может быть одним из двух, конечным или абстрактным.

Давайте посмотрим на пример.

Блок Finally

В Java, Finally, является необязательным блоком, который используется для обработки исключений. Обычно ему предшествует блок try-catch. Блок finally используется для выполнения важного кода, такого как очистка ресурса или освобождение использования памяти и т. д.

Блок finally будет выполняться независимо от того, обрабатывается ли исключение или нет. Таким образом, упаковка кодов очистки в блок finally считается хорошей практикой. Вы также можете использовать его с блоком try без необходимости использовать блок catch вместе с ним.

Метод Finalize

Finalize – это защищенный нестатический метод, который определен в классе Object и, таким образом, доступен для всех без исключения объектов в Java. Этот метод вызывается сборщиком мусора до полного уничтожения объекта.

Иногда, объекту может потребоваться выполнить какую-то важную задачу, такую как закрытие открытого соединения, освобождение ресурса и т. д., Прежде чем он будет уничтожен. Если эти задачи не будут выполнены, это может снизить эффективность программы.

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

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

В заключение я добавил сравнение всех трех ключевых слов, которое поможет вам быстро определить основные различия.

Name already in use

JBook / object / finalize.md

  • Go to file T
  • Go to line L
  • Copy path
  • Copy permalink
  • Open with Desktop
  • View raw
  • Copy raw contents Copy raw contents

Copy raw contents

Copy raw contents

Данный метод вызывается Garbage Collector (далее — просто GC ) тогда, когда GC полагает, что объект более не нужен, никем не используется и его пора утилизировать.

Объявление метода в Java 8 выглядит следующим образом:

На первый взгляд, может показаться, что это отличный метод, в который удобно поместить закрытие ресурсов и все, что нужно освобождать/удалять при уничтожении класса. Но это впечатление обманчиво. Более того, использование finalize подвержено ошибкам, а в версиях Java 9+ метод и вовсе помечен как @Deprecated(since=»9″) , т.е устаревший и не рекомендуемый к использованию.

Почему finalize не используется

Прежде всего потому что у нас нет НИКАКИХ гарантий, что этот метод вообще вызовется. Это легко может произойти, если у нас где-то в коде есть забытая ссылка на объект: мы про ссылку ничего не знаем, но она существует и GC не будет удалять этот объект. Данный метод также вызван не будет, например, если приложение будет остановлено или экстренно завершено.

Еще одним камнем в огород использования finalize является то, что сейчас алгоритмы сборки мусора изменились и она может происходить редко. А это значит, что большую часть времени ресурсы не будут освобождены. А представьте, что эти ресурсы — это подключения к серверу базы данных? В таком случае это будет негативно влиять на производительность не только вашего приложения, но и сервера базы данных.

Добавим еще то, что нет никаких гарантий в каком порядке будут вызваны методы финализации для группы объектов, поэтому возможны ситуация с deadlock -ом.

Также, чрезмерное использование finalize влияет на производительность и даже быть причиной падения программы:

Метод finalize не вызывается GC напрямую, а добавляет объекты в список, вызывая java.lang.ref.Finalizer.register(Object) .

Объект класса java.lang.ref.Finalizer представляет собой ссылку на объект, для которого надо вызвать finalize , и хранит ссылки на следующий и предыдущий Finalizer , формируя двусвязный список.

Вызов finalize происходит в отдельном потоке java.lang.ref.Finalizer.FinalizerThread , вызовы finalize идут последовательно так, как добавлялись (но как будут вызваны методы для группы объектов не известно, так как кто в каком порядке из объектов добавился — неизвестно). После вызова метода и его отработки, java.lang.ref.Finalizer на объекте будет удален из двусвязного списка финализаторов.

Поэтому, если finalize зависает, то зависнет именно FinalizerThread , если класс имеет пустой метод finalize , то JVM данный метод легко оптимизирует (удаляет), поэтому объекты такого класса будут и дальше удаляться, если же метод не пуст, то добавляются в список и ждут, пока все не отвиснет или не упадет окончательно, либо мы вообще не завершим наше приложение.

Именно поэтому, если в finalize методе произойдет блокировка (например, deadlock), то GC не перестанет работать.

Отсюда же и проблемы с производительностью: при первом вызове сборщика мусора, объекты с finalize не удаляются, а помещаются в очередь на финализацию, после чего финализируются и только при втором вызове сборщика мусора уже очищаются.

Представим, что в finalize мы написали какую-то долгую и большую операцию и получим ту самую проблему с OutOfMemoryError , описанную выше!

При этом мы в finalize можем и добавить ссылку на текущий объект куда-то и тем самым ‘воскресить’ его! Делать это, разумеется, ни в коем случае не следует!

При этом, если вы считаете, что если вы не пользуетесь finalize и вы с этим никогда не столкнетесь, то вот вам пример из java.io.FileInputStream :

И даже, если вы явно вызываете close , то метод и финализация все равно будут вызваны, а значит и повлияет на производительность!

Аналогично сделано и в java.io.FileOutputStream , подробнее об этом.

  • Использовать статические фабричные методы у java.nio.file.Files : Files.newInputStream и Files.newOutputStream
  • Перейти на Java 10+ , где данный метод у этих классов пустой и помечен как deprecated .

Поэтому внимательно следите за классами, которые вы используете и тем, что внутри этих классов.

Class Object

The actual result type is Class<? extends |X|> where |X| is the erasure of the static type of the expression on which getClass is called. For example, no cast is required in this code fragment:

Number n = 0;
Class<? extends Number> c = n.getClass();

hashCode

  • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
  • If two objects are equal according to the equals method, then calling the hashCode method on each of the two objects must produce the same integer result.
  • It is not required that if two objects are unequal according to the equals method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.

equals

  • It is reflexive: for any non-null reference value x , x.equals(x) should return true .
  • It is symmetric: for any non-null reference values x and y , x.equals(y) should return true if and only if y.equals(x) returns true .
  • It is transitive: for any non-null reference values x , y , and z , if x.equals(y) returns true and y.equals(z) returns true , then x.equals(z) should return true .
  • It is consistent: for any non-null reference values x and y , multiple invocations of x.equals(y) consistently return true or consistently return false , provided no information used in equals comparisons on the objects is modified.
  • For any non-null reference value x , x.equals(null) should return false .

An equivalence relation partitions the elements it operates on into equivalence classes; all the members of an equivalence class are equal to each other. Members of an equivalence class are substitutable for each other, at least for some purposes.

clone

By convention, the returned object should be obtained by calling super.clone . If a class and all of its superclasses (except Object ) obey this convention, it will be the case that x.clone().getClass() == x.getClass() .

By convention, the object returned by this method should be independent of this object (which is being cloned). To achieve this independence, it may be necessary to modify one or more fields of the object returned by super.clone before returning it. Typically, this means copying any mutable objects that comprise the internal «deep structure» of the object being cloned and replacing the references to these objects with references to the copies. If a class contains only primitive fields or references to immutable objects, then it is usually the case that no fields in the object returned by super.clone need to be modified.

The class Object does not itself implement the interface Cloneable , so calling the clone method on an object whose class is Object will result in throwing an exception at run time.

toString

notify

The awakened thread will not be able to proceed until the current thread relinquishes the lock on this object. The awakened thread will compete in the usual manner with any other threads that might be actively competing to synchronize on this object; for example, the awakened thread enjoys no reliable privilege or disadvantage in being the next thread to lock this object.

  • By executing a synchronized instance method of that object.
  • By executing the body of a synchronized statement that synchronizes on the object.
  • For objects of type Class, by executing a static synchronized method of that class.

Only one thread at a time can own an object’s monitor.

notifyAll

The awakened threads will not be able to proceed until the current thread relinquishes the lock on this object. The awakened threads will compete in the usual manner with any other threads that might be actively competing to synchronize on this object; for example, the awakened threads enjoy no reliable privilege or disadvantage in being the next thread to lock this object.

This method should only be called by a thread that is the owner of this object’s monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.

In all respects, this method behaves as if wait(0L, 0) had been called. See the specification of the wait(long, int) method for details.

In all respects, this method behaves as if wait(timeoutMillis, 0) had been called. See the specification of the wait(long, int) method for details.

The current thread must own this object’s monitor lock. See the notify method for a description of the ways in which a thread can become the owner of a monitor lock.

This method causes the current thread (referred to here as T ) to place itself in the wait set for this object and then to relinquish any and all synchronization claims on this object. Note that only the locks on this object are relinquished; any other objects on which the current thread may be synchronized remain locked while the thread waits.

  • Some other thread invokes the notify method for this object and thread T happens to be arbitrarily chosen as the thread to be awakened.
  • Some other thread invokes the notifyAll method for this object.
  • Some other thread interrupts thread T .
  • The specified amount of real time has elapsed, more or less. The amount of real time, in nanoseconds, is given by the expression 1000000 * timeoutMillis + nanos . If timeoutMillis and nanos are both zero, then real time is not taken into consideration and the thread waits until awakened by one of the other causes.
  • Thread T is awakened spuriously. (See below.)

The thread T is then removed from the wait set for this object and re-enabled for thread scheduling. It competes in the usual manner with other threads for the right to synchronize on the object; once it has regained control of the object, all its synchronization claims on the object are restored to the status quo ante — that is, to the situation as of the time that the wait method was invoked. Thread T then returns from the invocation of the wait method. Thus, on return from the wait method, the synchronization state of the object and of thread T is exactly as it was when the wait method was invoked.

A thread can wake up without being notified, interrupted, or timing out, a so-called spurious wakeup. While this will rarely occur in practice, applications must guard against it by testing for the condition that should have caused the thread to be awakened, and continuing to wait if the condition is not satisfied. See the example below.

For more information on this topic, see section 14.2, «Condition Queues,» in Brian Goetz and others’ Java Concurrency in Practice (Addison-Wesley, 2006) or Item 81 in Joshua Bloch’s Effective Java, Third Edition (Addison-Wesley, 2018).

If the current thread is interrupted by any thread before or while it is waiting, then an InterruptedException is thrown. The interrupted status of the current thread is cleared when this exception is thrown. This exception is not thrown until the lock status of this object has been restored as described above.

finalize

Subclasses that override finalize to perform cleanup should use alternative cleanup mechanisms and remove the finalize method. Use Cleaner and PhantomReference as safer ways to release resources when an object becomes unreachable. Alternatively, add a close method to explicitly release resources, and implement AutoCloseable to enable use of the try -with-resources statement.

This method will remain in place until finalizers have been removed from most existing code.

When running in a Java virtual machine in which finalization has been disabled or removed, the garbage collector will never call finalize() . In a Java virtual machine in which finalization is enabled, the garbage collector might call finalize only after an indefinite delay.

The general contract of finalize is that it is invoked if and when the Java virtual machine has determined that there is no longer any means by which this object can be accessed by any thread that has not yet died, except as a result of an action taken by the finalization of some other object or class which is ready to be finalized. The finalize method may take any action, including making this object available again to other threads; the usual purpose of finalize , however, is to perform cleanup actions before the object is irrevocably discarded. For example, the finalize method for an object that represents an input/output connection might perform explicit I/O transactions to break the connection before the object is permanently discarded.

The finalize method of class Object performs no special action; it simply returns normally. Subclasses of Object may override this definition.

The Java programming language does not guarantee which thread will invoke the finalize method for any given object. It is guaranteed, however, that the thread that invokes finalize will not be holding any user-visible synchronization locks when finalize is invoked. If an uncaught exception is thrown by the finalize method, the exception is ignored and finalization of that object terminates.

After the finalize method has been invoked for an object, no further action is taken until the Java virtual machine has again determined that there is no longer any means by which this object can be accessed by any thread that has not yet died, including possible actions by other objects or classes which are ready to be finalized, at which point the object may be discarded.

The finalize method is never invoked more than once by a Java virtual machine for any given object.

Any exception thrown by the finalize method causes the finalization of this object to be halted, but is otherwise ignored.

A subclass should avoid overriding the finalize method unless the subclass embeds non-heap resources that must be cleaned up before the instance is collected. Finalizer invocations are not automatically chained, unlike constructors. If a subclass overrides finalize it must invoke the superclass finalizer explicitly. To guard against exceptions prematurely terminating the finalize chain, the subclass should use a try-finally block to ensure super.finalize() is always invoked. For example,

Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples. Other versions.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2023, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *