1 /*
2 * Copyright (c) 1994, 2024, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26 package java.lang;
27
28 import jdk.internal.vm.annotation.AOTSafeClassInitializer;
29 import jdk.internal.vm.annotation.IntrinsicCandidate;
30
31 /**
32 * Class {@code Object} is the root of the class hierarchy.
33 * Every class has {@code Object} as a superclass. All objects,
34 * including arrays, implement the methods of this class.
35 *
36 * <div class="preview-block">
37 * <div class="preview-comment">
38 * When preview features are enabled, subclasses of {@code java.lang.Object} can be either
39 * an {@linkplain Class#isIdentity identity class} or a {@linkplain Class#isValue value class}.
40 * See {@jls The Java Language Specification 8.1.1.5 Value Classes}.
41 * Use of value class instances for synchronization, mutexes, or with
42 * {@linkplain java.lang.ref.Reference object references} result in
43 * {@link IdentityException}.
44 * </div>
45 * </div>
46 *
47 * @see java.lang.Class
48 * @since 1.0
49 */
50 @AOTSafeClassInitializer // for hierarchy checks
51 public class Object {
52
53 /**
54 * Constructs a new object.
55 */
56 @IntrinsicCandidate
57 public Object() {}
58
59 /**
60 * Returns the runtime class of this {@code Object}. The returned
61 * {@code Class} object is the object that is locked by {@code
62 * static synchronized} methods of the represented class.
63 *
64 * <p><b>The actual result type is {@code Class<? extends |X|>}
65 * where {@code |X|} is the erasure of the static type of the
66 * expression on which {@code getClass} is called.</b> For
67 * example, no cast is required in this code fragment:</p>
68 *
69 * <p>
70 * {@code Number n = 0; }<br>
71 * {@code Class<? extends Number> c = n.getClass(); }
72 * </p>
73 *
74 * @return The {@code Class} object that represents the runtime
75 * class of this object.
76 * @jls 15.8.2 Class Literals
77 */
78 @IntrinsicCandidate
79 public final native Class<?> getClass();
80
81 /**
82 * {@return a hash code value for this object} This method is
83 * supported for the benefit of hash tables such as those provided by
84 * {@link java.util.HashMap}.
85 * <p>
86 * The general contract of {@code hashCode} is:
87 * <ul>
88 * <li>Whenever it is invoked on the same object more than once during
89 * an execution of a Java application, the {@code hashCode} method
90 * must consistently return the same integer, provided no information
91 * used in {@code equals} comparisons on the object is modified.
92 * This integer need not remain consistent from one execution of an
93 * application to another execution of the same application.
94 * <li>If two objects are equal according to the {@link
95 * #equals(Object) equals} method, then calling the {@code
96 * hashCode} method on each of the two objects must produce the
97 * same integer result.
98 * <li>It is <em>not</em> required that if two objects are unequal
99 * according to the {@link #equals(Object) equals} method, then
100 * calling the {@code hashCode} method on each of the two objects
101 * must produce distinct integer results. However, the programmer
102 * should be aware that producing distinct integer results for
103 * unequal objects may improve the performance of hash tables.
104 * </ul>
105 *
106 * @implSpec
107 * As far as is reasonably practical, the {@code hashCode} method defined
108 * by class {@code Object} returns distinct integers for distinct objects.
109 *
110 * @apiNote
111 * The {@link java.util.Objects#hash(Object...) hash} and {@link
112 * java.util.Objects#hashCode(Object) hashCode} methods of {@link
113 * java.util.Objects} can be used to help construct simple hash codes.
114 *
115 * @see java.lang.Object#equals(java.lang.Object)
116 * @see java.lang.System#identityHashCode
117 */
118 @IntrinsicCandidate
119 public native int hashCode();
120
121 /**
122 * Indicates whether some other object is "equal to" this one.
123 * <p>
124 * The {@code equals} method implements an <dfn>{@index "equivalence relation"}</dfn>
125 * on non-null object references:
126 * <ul>
127 * <li>It is <i>reflexive</i>: for any non-null reference value
128 * {@code x}, {@code x.equals(x)} should return
129 * {@code true}.
130 * <li>It is <i>symmetric</i>: for any non-null reference values
131 * {@code x} and {@code y}, {@code x.equals(y)}
132 * should return {@code true} if and only if
133 * {@code y.equals(x)} returns {@code true}.
134 * <li>It is <i>transitive</i>: for any non-null reference values
135 * {@code x}, {@code y}, and {@code z}, if
136 * {@code x.equals(y)} returns {@code true} and
137 * {@code y.equals(z)} returns {@code true}, then
138 * {@code x.equals(z)} should return {@code true}.
139 * <li>It is <i>consistent</i>: for any non-null reference values
140 * {@code x} and {@code y}, multiple invocations of
141 * {@code x.equals(y)} consistently return {@code true}
142 * or consistently return {@code false}, provided no
143 * information used in {@code equals} comparisons on the
144 * objects is modified.
145 * <li>For any non-null reference value {@code x},
146 * {@code x.equals(null)} should return {@code false}.
147 * </ul>
148 *
149 * <p>
150 * An equivalence relation partitions the elements it operates on
151 * into <i>equivalence classes</i>; all the members of an
152 * equivalence class are equal to each other. Members of an
153 * equivalence class are substitutable for each other, at least
154 * for some purposes.
155 *
156 * @implSpec
157 * The {@code equals} method for class {@code Object} implements
158 * the most discriminating possible equivalence relation on objects;
159 * that is, for any non-null reference values {@code x} and
160 * {@code y}, this method returns {@code true} if and only
161 * if {@code x} and {@code y} refer to the same object
162 * ({@code x == y} has the value {@code true}).
163 *
164 * In other words, under the reference equality equivalence
165 * relation, each equivalence class only has a single element.
166 *
167 * @apiNote
168 * It is generally necessary to override the {@link #hashCode() hashCode}
169 * method whenever this method is overridden, so as to maintain the
170 * general contract for the {@code hashCode} method, which states
171 * that equal objects must have equal hash codes.
172 * <p>The two-argument {@link java.util.Objects#equals(Object,
173 * Object) Objects.equals} method implements an equivalence relation
174 * on two possibly-null object references.
175 *
176 * @param obj the reference object with which to compare.
177 * @return {@code true} if this object is the same as the obj
178 * argument; {@code false} otherwise.
179 * @see #hashCode()
180 * @see java.util.HashMap
181 */
182 public boolean equals(Object obj) {
183 return (this == obj);
184 }
185
186 /**
187 * Creates and returns a copy of this object. The precise meaning
188 * of "copy" may depend on the class of the object. The general
189 * intent is that, for any object {@code x}, the expression:
190 * <blockquote>
191 * <pre>
192 * x.clone() != x</pre></blockquote>
193 * will be true, and that the expression:
194 * <blockquote>
195 * <pre>
196 * x.clone().getClass() == x.getClass()</pre></blockquote>
197 * will be {@code true}, but these are not absolute requirements.
198 * While it is typically the case that:
199 * <blockquote>
200 * <pre>
201 * x.clone().equals(x)</pre></blockquote>
202 * will be {@code true}, this is not an absolute requirement.
203 * <p>
204 * By convention, the returned object should be obtained by calling
205 * {@code super.clone}. If a class and all of its superclasses (except
206 * {@code Object}) obey this convention, it will be the case that
207 * {@code x.clone().getClass() == x.getClass()}.
208 * <p>
209 * By convention, the object returned by this method should be independent
210 * of this object (which is being cloned). To achieve this independence,
211 * it may be necessary to modify one or more fields of the object returned
212 * by {@code super.clone} before returning it. Typically, this means
213 * copying any mutable objects that comprise the internal "deep structure"
214 * of the object being cloned and replacing the references to these
215 * objects with references to the copies. If a class contains only
216 * primitive fields or references to immutable objects, then it is usually
217 * the case that no fields in the object returned by {@code super.clone}
218 * need to be modified.
219 *
220 * @implSpec
221 * The method {@code clone} for class {@code Object} performs a
222 * specific cloning operation. First, if the class of this object does
223 * not implement the interface {@code Cloneable}, then a
224 * {@code CloneNotSupportedException} is thrown. Note that all arrays
225 * are considered to implement the interface {@code Cloneable} and that
226 * the return type of the {@code clone} method of an array type {@code T[]}
227 * is {@code T[]} where T is any reference or primitive type.
228 * Otherwise, this method creates a new instance of the class of this
229 * object and initializes all its fields with exactly the contents of
230 * the corresponding fields of this object, as if by assignment; the
231 * contents of the fields are not themselves cloned. Thus, this method
232 * performs a "shallow copy" of this object, not a "deep copy" operation.
233 * <p>
234 * The class {@code Object} does not itself implement the interface
235 * {@code Cloneable}, so calling the {@code clone} method on an object
236 * whose class is {@code Object} will result in throwing an
237 * exception at run time.
238 *
239 * @return a clone of this instance.
240 * @throws CloneNotSupportedException if the object's class does not
241 * support the {@code Cloneable} interface. Subclasses
242 * that override the {@code clone} method can also
243 * throw this exception to indicate that an instance cannot
244 * be cloned.
245 * @see java.lang.Cloneable
246 */
247 @IntrinsicCandidate
248 protected native Object clone() throws CloneNotSupportedException;
249
250 /**
251 * {@return a string representation of the object}
252 *
253 * Satisfying this method's contract implies a non-{@code null}
254 * result must be returned.
255 *
256 * @apiNote
257 * In general, the
258 * {@code toString} method returns a string that
259 * "textually represents" this object. The result should
260 * be a concise but informative representation that is easy for a
261 * person to read.
262 * It is recommended that all subclasses override this method.
263 * The string output is not necessarily stable over time or across
264 * JVM invocations.
265 * @implSpec
266 * The {@code toString} method for class {@code Object}
267 * returns a string consisting of the name of the class of which the
268 * object is an instance, the at-sign character `{@code @}', and
269 * the unsigned hexadecimal representation of the hash code of the
270 * object. In other words, this method returns a string equal to the
271 * value of:
272 * {@snippet lang=java :
273 * getClass().getName() + '@' + Integer.toHexString(hashCode())
274 * }
275 * The {@link java.util.Objects#toIdentityString(Object)
276 * Objects.toIdentityString} method returns the string for an
277 * object equal to the string that would be returned if neither
278 * the {@code toString} nor {@code hashCode} methods were
279 * overridden by the object's class.
280 */
281 public String toString() {
282 return getClass().getName() + "@" + Integer.toHexString(hashCode());
283 }
284
285 /**
286 * Wakes up a single thread that is waiting on this object's
287 * monitor. If any threads are waiting on this object, one of them
288 * is chosen to be awakened. The choice is arbitrary and occurs at
289 * the discretion of the implementation. A thread waits on an object's
290 * monitor by calling one of the {@code wait} methods.
291 * <p>
292 * The awakened thread will not be able to proceed until the current
293 * thread relinquishes the lock on this object. The awakened thread will
294 * compete in the usual manner with any other threads that might be
295 * actively competing to synchronize on this object; for example, the
296 * awakened thread enjoys no reliable privilege or disadvantage in being
297 * the next thread to lock this object.
298 * <p>
299 * This method should only be called by a thread that is the owner
300 * of this object's monitor. A thread becomes the owner of the
301 * object's monitor in one of three ways:
302 * <ul>
303 * <li>By executing a synchronized instance method of that object.
304 * <li>By executing the body of a {@code synchronized} statement
305 * that synchronizes on the object.
306 * <li>For objects of type {@code Class,} by executing a
307 * static synchronized method of that class.
308 * </ul>
309 * <p>
310 * Only one thread at a time can own an object's monitor.
311 * <div class="preview-block">
312 * <div class="preview-comment">
313 * If this object is a {@linkplain Class#isValue() value object},
314 * it does does not have a monitor, an {@code IllegalMonitorStateException} is thrown.
315 * </div>
316 * </div>
317 *
318 * @throws IllegalMonitorStateException if the current thread is not
319 * the owner of this object's monitor or
320 * if this object is a {@linkplain Class#isValue() value object}.
321 * @see java.lang.Object#notifyAll()
322 * @see java.lang.Object#wait()
323 */
324 @IntrinsicCandidate
325 public final native void notify();
326
327 /**
328 * Wakes up all threads that are waiting on this object's monitor. A
329 * thread waits on an object's monitor by calling one of the
330 * {@code wait} methods.
331 * <p>
332 * The awakened threads will not be able to proceed until the current
333 * thread relinquishes the lock on this object. The awakened threads
334 * will compete in the usual manner with any other threads that might
335 * be actively competing to synchronize on this object; for example,
336 * the awakened threads enjoy no reliable privilege or disadvantage in
337 * being the next thread to lock this object.
338 * <p>
339 * This method should only be called by a thread that is the owner
340 * of this object's monitor. See the {@code notify} method for a
341 * description of the ways in which a thread can become the owner of
342 * a monitor.
343 *
344 * <div class="preview-block">
345 * <div class="preview-comment">
346 * If this object is a {@linkplain Class#isValue() value object},
347 * it does does not have a monitor, an {@code IllegalMonitorStateException} is thrown.
348 * </div>
349 * </div>
350 *
351 * @throws IllegalMonitorStateException if the current thread is not
352 * the owner of this object's monitor or
353 * if this object is a {@linkplain Class#isValue() value object}.
354 * @see java.lang.Object#notify()
355 * @see java.lang.Object#wait()
356 */
357 @IntrinsicCandidate
358 public final native void notifyAll();
359
360 /**
361 * Causes the current thread to wait until it is awakened, typically
362 * by being <em>notified</em> or <em>interrupted</em>.
363 * <p>
364 * In all respects, this method behaves as if {@code wait(0L, 0)}
365 * had been called. See the specification of the {@link #wait(long, int)} method
366 * for details.
367 *
368 * <div class="preview-block">
369 * <div class="preview-comment">
370 * If this object is a {@linkplain Class#isValue() value object},
371 * it does does not have a monitor, an {@code IllegalMonitorStateException} is thrown.
372 * </div>
373 * </div>
374 *
375 * @throws IllegalMonitorStateException if the current thread is not
376 * the owner of the object's monitor or
377 * if this object is a {@linkplain Class#isValue() value object}.
378 * @throws InterruptedException if any thread interrupted the current thread before or
379 * while the current thread was waiting. The <em>interrupted status</em> of the
380 * current thread is cleared when this exception is thrown.
381 * @see #notify()
382 * @see #notifyAll()
383 * @see #wait(long)
384 * @see #wait(long, int)
385 */
386 public final void wait() throws InterruptedException {
387 wait(0L);
388 }
389
390 /**
391 * Causes the current thread to wait until it is awakened, typically
392 * by being <em>notified</em> or <em>interrupted</em>, or until a
393 * certain amount of real time has elapsed.
394 * <p>
395 * In all respects, this method behaves as if {@code wait(timeoutMillis, 0)}
396 * had been called. See the specification of the {@link #wait(long, int)} method
397 * for details.
398 *
399 * <div class="preview-block">
400 * <div class="preview-comment">
401 * If this object is a {@linkplain Class#isValue() value object},
402 * it does does not have a monitor, an {@code IllegalMonitorStateException} is thrown.
403 * </div>
404 * </div>
405 *
406 * @param timeoutMillis the maximum time to wait, in milliseconds
407 * @throws IllegalArgumentException if {@code timeoutMillis} is negative
408 * @throws IllegalMonitorStateException if the current thread is not
409 * the owner of the object's monitor or
410 * if this object is a {@linkplain Class#isValue() value object}.
411 * @throws InterruptedException if any thread interrupted the current thread before or
412 * while the current thread was waiting. The <em>interrupted status</em> of the
413 * current thread is cleared when this exception is thrown.
414 * @see #notify()
415 * @see #notifyAll()
416 * @see #wait()
417 * @see #wait(long, int)
418 */
419 public final void wait(long timeoutMillis) throws InterruptedException {
420 if (timeoutMillis < 0) {
421 throw new IllegalArgumentException("timeout value is negative");
422 }
423
424 if (Thread.currentThread() instanceof VirtualThread vthread) {
425 try {
426 wait0(timeoutMillis);
427 } catch (InterruptedException e) {
428 // virtual thread's interrupt status needs to be cleared
429 vthread.getAndClearInterrupt();
430 throw e;
431 }
432 } else {
433 wait0(timeoutMillis);
434 }
435 }
436
437 // final modifier so method not in vtable
438 private final native void wait0(long timeoutMillis) throws InterruptedException;
439
440 /**
441 * Causes the current thread to wait until it is awakened, typically
442 * by being <em>notified</em> or <em>interrupted</em>, or until a
443 * certain amount of real time has elapsed.
444 * <p>
445 * The current thread must own this object's monitor lock. See the
446 * {@link #notify notify} method for a description of the ways in which
447 * a thread can become the owner of a monitor lock.
448 * <p>
449 * This method causes the current thread (referred to here as <var>T</var>) to
450 * place itself in the wait set for this object and then to relinquish any
451 * and all synchronization claims on this object. Note that only the locks
452 * on this object are relinquished; any other objects on which the current
453 * thread may be synchronized remain locked while the thread waits.
454 * <p>
455 * Thread <var>T</var> then becomes disabled for thread scheduling purposes
456 * and lies dormant until one of the following occurs:
457 * <ul>
458 * <li>Some other thread invokes the {@code notify} method for this
459 * object and thread <var>T</var> happens to be arbitrarily chosen as
460 * the thread to be awakened.
461 * <li>Some other thread invokes the {@code notifyAll} method for this
462 * object.
463 * <li>Some other thread {@linkplain Thread#interrupt() interrupts}
464 * thread <var>T</var>.
465 * <li>The specified amount of real time has elapsed, more or less.
466 * The amount of real time, in nanoseconds, is given by the expression
467 * {@code 1000000 * timeoutMillis + nanos}. If {@code timeoutMillis} and {@code nanos}
468 * are both zero, then real time is not taken into consideration and the
469 * thread waits until awakened by one of the other causes.
470 * <li>Thread <var>T</var> is awakened spuriously. (See below.)
471 * </ul>
472 * <p>
473 * The thread <var>T</var> is then removed from the wait set for this
474 * object and re-enabled for thread scheduling. It competes in the
475 * usual manner with other threads for the right to synchronize on the
476 * object; once it has regained control of the object, all its
477 * synchronization claims on the object are restored to the status quo
478 * ante - that is, to the situation as of the time that the {@code wait}
479 * method was invoked. Thread <var>T</var> then returns from the
480 * invocation of the {@code wait} method. Thus, on return from the
481 * {@code wait} method, the synchronization state of the object and of
482 * thread {@code T} is exactly as it was when the {@code wait} method
483 * was invoked.
484 * <p>
485 * A thread can wake up without being notified, interrupted, or timing out, a
486 * so-called <em>spurious wakeup</em>. While this will rarely occur in practice,
487 * applications must guard against it by testing for the condition that should
488 * have caused the thread to be awakened, and continuing to wait if the condition
489 * is not satisfied. See the example below.
490 * <p>
491 * For more information on this topic, see section 14.2,
492 * "Condition Queues," in Brian Goetz and others' <cite>Java Concurrency
493 * in Practice</cite> (Addison-Wesley, 2006) or Item 81 in Joshua
494 * Bloch's <cite>Effective Java, Third Edition</cite> (Addison-Wesley,
495 * 2018).
496 * <p>
497 * If the current thread is {@linkplain java.lang.Thread#interrupt() interrupted}
498 * by any thread before or while it is waiting, then an {@code InterruptedException}
499 * is thrown. The <em>interrupted status</em> of the current thread is cleared when
500 * this exception is thrown. This exception is not thrown until the lock status of
501 * this object has been restored as described above.
502 *
503 * @apiNote
504 * The recommended approach to waiting is to check the condition being awaited in
505 * a {@code while} loop around the call to {@code wait}, as shown in the example
506 * below. Among other things, this approach avoids problems that can be caused
507 * by spurious wakeups.
508 *
509 * {@snippet lang=java :
510 * synchronized (obj) {
511 * while ( <condition does not hold and timeout not exceeded> ) {
512 * long timeoutMillis = ... ; // recompute timeout values
513 * int nanos = ... ;
514 * obj.wait(timeoutMillis, nanos);
515 * }
516 * ... // Perform action appropriate to condition or timeout
517 * }
518 * }
519 *
520 * <div class="preview-block">
521 * <div class="preview-comment">
522 * If this object is a {@linkplain Class#isValue() value object},
523 * it does does not have a monitor, an {@code IllegalMonitorStateException} is thrown.
524 * </div>
525 * </div>
526 * @param timeoutMillis the maximum time to wait, in milliseconds
527 * @param nanos additional time, in nanoseconds, in the range 0-999999 inclusive
528 * @throws IllegalArgumentException if {@code timeoutMillis} is negative,
529 * or if the value of {@code nanos} is out of range
530 * @throws IllegalMonitorStateException if the current thread is not
531 * the owner of the object's monitor or
532 * if this object is a {@linkplain Class#isValue() value object}.
533 * @throws InterruptedException if any thread interrupted the current thread before or
534 * while the current thread was waiting. The <em>interrupted status</em> of the
535 * current thread is cleared when this exception is thrown.
536 * @see #notify()
537 * @see #notifyAll()
538 * @see #wait()
539 * @see #wait(long)
540 */
541 public final void wait(long timeoutMillis, int nanos) throws InterruptedException {
542 if (timeoutMillis < 0) {
543 throw new IllegalArgumentException("timeoutMillis value is negative");
544 }
545
546 if (nanos < 0 || nanos > 999999) {
547 throw new IllegalArgumentException(
548 "nanosecond timeout value out of range");
549 }
550
551 if (nanos > 0 && timeoutMillis < Long.MAX_VALUE) {
552 timeoutMillis++;
553 }
554
555 wait(timeoutMillis);
556 }
557
558 /**
559 * Called by the garbage collector on an object when garbage collection
560 * determines that there are no more references to the object.
561 * A subclass overrides the {@code finalize} method to dispose of
562 * system resources or to perform other cleanup.
563 * <p>
564 * <b>When running in a Java virtual machine in which finalization has been
565 * disabled or removed, the garbage collector will never call
566 * {@code finalize()}. In a Java virtual machine in which finalization is
567 * enabled, the garbage collector might call {@code finalize} only after an
568 * indefinite delay.</b>
569 * <p>
570 * The general contract of {@code finalize} is that it is invoked
571 * if and when the Java virtual
572 * machine has determined that there is no longer any
573 * means by which this object can be accessed by any thread that has
574 * not yet died, except as a result of an action taken by the
575 * finalization of some other object or class which is ready to be
576 * finalized. The {@code finalize} method may take any action, including
577 * making this object available again to other threads; the usual purpose
578 * of {@code finalize}, however, is to perform cleanup actions before
579 * the object is irrevocably discarded. For example, the finalize method
580 * for an object that represents an input/output connection might perform
581 * explicit I/O transactions to break the connection before the object is
582 * permanently discarded.
583 * <p>
584 * The {@code finalize} method of class {@code Object} performs no
585 * special action; it simply returns normally. Subclasses of
586 * {@code Object} may override this definition.
587 * <p>
588 * The Java programming language does not guarantee which thread will
589 * invoke the {@code finalize} method for any given object. It is
590 * guaranteed, however, that the thread that invokes finalize will not
591 * be holding any user-visible synchronization locks when finalize is
592 * invoked. If an uncaught exception is thrown by the finalize method,
593 * the exception is ignored and finalization of that object terminates.
594 * <p>
595 * After the {@code finalize} method has been invoked for an object, no
596 * further action is taken until the Java virtual machine has again
597 * determined that there is no longer any means by which this object can
598 * be accessed by any thread that has not yet died, including possible
599 * actions by other objects or classes which are ready to be finalized,
600 * at which point the object may be discarded.
601 * <p>
602 * The {@code finalize} method is never invoked more than once by a Java
603 * virtual machine for any given object.
604 * <p>
605 * Any exception thrown by the {@code finalize} method causes
606 * the finalization of this object to be halted, but is otherwise
607 * ignored.
608 *
609 * @apiNote
610 * Classes that embed non-heap resources have many options
611 * for cleanup of those resources. The class must ensure that the
612 * lifetime of each instance is longer than that of any resource it embeds.
613 * {@link java.lang.ref.Reference#reachabilityFence} can be used to ensure that
614 * objects remain reachable while resources embedded in the object are in use.
615 * <p>
616 * A subclass should avoid overriding the {@code finalize} method
617 * unless the subclass embeds non-heap resources that must be cleaned up
618 * before the instance is collected.
619 * Finalizer invocations are not automatically chained, unlike constructors.
620 * If a subclass overrides {@code finalize} it must invoke the superclass
621 * finalizer explicitly.
622 * To guard against exceptions prematurely terminating the finalize chain,
623 * the subclass should use a {@code try-finally} block to ensure
624 * {@code super.finalize()} is always invoked. For example,
625 * {@snippet lang="java":
626 * @Override
627 * protected void finalize() throws Throwable {
628 * try {
629 * ... // cleanup subclass state
630 * } finally {
631 * super.finalize();
632 * }
633 * }
634 * }
635 *
636 * @deprecated Finalization is deprecated and subject to removal in a future
637 * release. The use of finalization can lead to problems with security,
638 * performance, and reliability.
639 * See <a href="https://openjdk.org/jeps/421">JEP 421</a> for
640 * discussion and alternatives.
641 * <p>
642 * Subclasses that override {@code finalize} to perform cleanup should use
643 * alternative cleanup mechanisms and remove the {@code finalize} method.
644 * Use {@link java.lang.ref.Cleaner} and
645 * {@link java.lang.ref.PhantomReference} as safer ways to release resources
646 * when an object becomes unreachable. Alternatively, add a {@code close}
647 * method to explicitly release resources, and implement
648 * {@code AutoCloseable} to enable use of the {@code try}-with-resources
649 * statement.
650 * <p>
651 * This method will remain in place until finalizers have been removed from
652 * most existing code.
653 *
654 * @throws Throwable the {@code Exception} raised by this method
655 * @see java.lang.ref.WeakReference
656 * @see java.lang.ref.PhantomReference
657 * @jls 12.6 Finalization of Class Instances
658 */
659 @Deprecated(since="9", forRemoval=true)
660 protected void finalize() throws Throwable { }
661 }