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