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