In-depth study of Java.lang.Object class

Source: Internet
Author: User
Tags instance method

Preface: Java's class library is becoming larger, and contains countless classes and interfaces. But there are some very important classes and interfaces that are the core of the Java class Library. Common string, Object, class, Collection, ClassLoader, System, Runtime ..., mastering classes is the basis of the flexible Java language. And these classes are generally well understood and used, need to do in-depth research and practice to master.

overview:
       < Span style= "color: #0000ff; padding:0px; margin:0px ">object class is the ancestor of all Java classes. Each class uses Object as a superclass. All objects, including arrays, implement methods of this class.
      You can use a variable of type object to point to an object of any type.
      the object class has a default constructor method Pubilc object (), when the subclass instance is constructed, Will call this default constructor first.
      Variables of the object class can only be used as generic holders of various values. To do anything specific to them, you need to know their original types and type conversions. For example:
      Object obj = new MyObject ();
      MyObject x = (MyObject) obj;

Second, API preview
Object ()
Default constructor method
Clone ()
Creates and returns a copy of this object.
Equals (Object obj)
Indicates whether a different object is "equal" to this object.
Finalize ()
This method is called by the object's garbage collector when the garbage collector determines that there are no more references to the object.
GetClass ()
Returns the run-time class of an object.
Hashcode ()
Returns the hash code value of the object.
Notify ()
Wakes up a single thread waiting on this object monitor.
Notifyall ()
Wakes all the threads waiting on this object monitor.
ToString ()
Returns the string representation of the object.
Wait ()
Causes the current thread to wait until other threads call the Notify () method of this object or the Notifyall () method.
Wait (long timeout)
Causes the current thread to wait until another thread calls this object's notify () method or the Notifyall () method, or exceeds the specified amount of time.
Wait (long timeout, int nanos)
Causes the current thread to wait until another thread calls this object's notify () method or the Notifyall () method, or some other thread interrupts the current thread, or has exceeded an actual amount of time.

Iii. instructions for use of the method
1. Equals () method: Used to test whether an object is equal to another object. Its implementation in the object class is to determine whether two objects point to the same piece of memory area. This test is not useful because the memory area is different, even for objects with the same content. If you want to test whether an object is equal, you need to override this method for a more meaningful comparison. For example
Class employee{
...//This example comes from "Java Core Technology" Volume One
public boolean equals (Object otherobj) {
Quick test whether it is the same object
if (this = = Otherobj) return true;
If an explicit argument is NULL, you must return False
if (otherobj = = null) reutrn false;
If the class does not match, it cannot be equal
if (getclass () = Otherobj.getclass ()) return false;

Now I know otherobj is a non-empty employee object.
Employee other = (employee) otherobj;

Test if all fields are equal
Return Name.equals (Other.name)
&& salary = = Other.salary
&& hireday.equals (Other.hireday);
}
}
The Java language specification requires the Equals method to have the following characteristics:
reflexivity : x,x.equals (x) should return true for any non-null reference value.
symmetry : x.equals (y) should return true for any non-null reference value x and Y, if and only if Y.equals (x) returns True.
transitivity : For any non-null reference value x, Y, and Z, if X.equals (y) returns true and Y.equals (z) returns True, then X.equals (z) should return true.
consistency : For any non-null reference value x and Y, multiple calls to X.equals (Y) always return TRUE or always return false, provided that the information used in the Equals comparison on the object has not been modified.
X,x.equals (NULL) should return FALSE for any non-null reference value.

As seen here, the above example is the standard implementation of the Equals method of the Java specification, and it is recommended to implement the Equals method of the class using the above example.

2, ToString (): Returns the string representation of the object. The ToString () method in the object class prints out the class name and the memory location of the object. Almost every class overrides the method to print a representation of the current state of the object. Most (not all) toString () methods follow the following format: class name [Field name = value, field name = value ...], of course, subclasses should define their own toString () method. For example:

Public String toString () {
Reurn "Employee[name=" + name + ", salary=" + salary + ", hireday=" + Hireday + "]";
}
The ToString () method is a very important debugging tool, and many classes in the standard class library define the ToString () method so that the programmer can get useful debugging information.


3. Clone (): Creates and returns a copy of this object. The exact meaning of a "copy" may depend on the class of the object. The purpose of doing this is, for any object x,

Expression: X.clone ()! = X is true, expression: X.clone (). GetClass () = = X.getclass () is also true, but these are not requirements that must be met.

In general: X.clone (). Equals (x) is true, but this is not a requirement that must be met.

4, Notify (): Wakes a single thread waiting on this object monitor. If all threads are waiting on this object, then one of the threads is chosen to wake up. The choice is arbitrary and occurs when a decision is made on the implementation. The thread waits on the object's monitor by calling one of the wait methods.
Until the current thread discards the lock on this object, it can continue to execute the awakened thread. The awakened thread competes with all other threads that are actively synchronizing on the object, for example, the thread that wakes up does not have a reliable privilege or disadvantage as the next thread that locks the object.

This method should be called only by threads that are the owner of this object monitor. A thread can be the owner of this object monitor by one of the following three methods:

    • By executing the synchronous instance method of this object.
    • The body of the statement that is synchronized by executing on this object synchronized .
    • For Class types of objects, you can do this by executing a synchronous static method of the class.

Only one thread can have a monitor for an object at a time.


5, Notifyall (): Wakes all the threads waiting on this object monitor. The thread wait waits on the object's monitor by calling one of the methods.

until the current thread discards the lock on this object, it can continue to execute the awakened thread. The awakened thread competes with all other threads that are actively synchronizing on the object, for example, the thread that wakes up does not have a reliable privilege or disadvantage as the next thread that locks the object.


6, wait (long timeout): Causes the current thread to wait before another thread calls this object's notify () method or the Notifyall () method, or exceeds the specified amount of time.
The current thread must have this object monitor.
This method causes the current thread (called T) to place itself in the object's wait set, and then discards all synchronization requirements on the object. For thread scheduling purposes, thread T is disabled and dormant until one of the following four scenarios occurs:

    • One of the other threads calls the Notify method of this object, and the thread T happens to be selected as the thread that is awakened.
    • One of the other threads calls the Notifyall method of this object.
    • Thread-Break T in one of the other threads.
    • The actual time specified has been reached. However, if timeout is zero, the actual time is not considered and the thread waits until the notification is received. Then, the thread T is removed from the object's waiting set and the thread is dispatched again. The thread then competes with other threads in a normal way to gain the right to synchronize on that object, and once control of the object is obtained, all its synchronous declarations on that object are restored to the previous state, which is the case when the wait method is called. Then, the thread T is returned from the call of the wait method. Therefore, when returning from the wait method, the synchronization state of the object and thread T is exactly the same as when the wait method is called.
The thread can also wake up with a so-called spurious wakeup (spurious wakeup) without being notified, interrupted, or timed out. Although this situation rarely occurs in practice, the application must prevent it from occurring by testing the condition that should cause the thread to be alerted, and then continue waiting if the condition is not met. In other words, the wait should always occur in the loop, as in the following example:
synchronized (obj) {
while (<condition does not hold>)
Obj.wait (timeout);
...//Perform action appropriate to condition
}


7, wait (long timeout, int Nanos): Causes the current thread to wait until another thread calls this object's notify () method or the Notifyall () method, or some other thread interrupts the current thread, or has exceeded an actual amount of time.

This method is similar to the wait method for a parameter, but it allows better control over the amount of time to wait for notification before discarding. The actual amount of time measured in nanoseconds can be calculated using the following formula:
1000000*timeout+nanos in all other respects, this method performs the same action as the Wait (long) method with one parameter. It should be noted that wait (0, 0) is the same as wait (0).

The current thread must have this object monitor. The thread publishes ownership of this monitor and waits for one of the following two conditions to occur:

    • Other threads wake up by calling the Notify method, or the Notifyall method notifies the waiting thread on this object's monitor.
    • Timeout milliseconds value and the sum of the Nanos nanosecond parameter values specify a time-out period that is exhausted.
The thread then waits to regain ownership of the monitor before it can continue execution.
For a version of a parameter, it is possible to implement interrupts and spurious wakes, and this method should always be used in loops:
synchronized (obj) {
while (<condition does not hold>)
Obj.wait (timeout, Nanos);
...//Perform action appropriate to condition
}

8, Wait (): Causes the current thread to wait before another thread calls this object's notify () method or the Notifyall () method. In other words, this method behaves as if it were only executing wait (0) calls.


The current thread must have this object monitor. The thread releases ownership of this monitor and waits until other threads wake up by calling the Notify method, or the Notifyall method notifies the thread waiting on this object's monitor. The thread then waits to regain ownership of the monitor before it can continue execution.


For a version of a parameter, it is possible to implement interrupts and spurious wakes, and this method should always be used in loops:
Synchronized (obj) {
while (<condition does not hold>)
Obj.wait ();
...//Perform action appropriate to condition
}


9. Finalize (): This method is called by the object's garbage collector when the garbage collector determines that there are no more references to the object. Subclasses override the Finalize method to configure system resources or perform other cleanup.
The general contract for finalize is that this method is called when the JAVATM virtual machine has determined that any thread that has not yet been terminated can no longer access the object through any method, unless an operation has been performed because of the finalization of another object or class that is ready to terminate. The Finalize method can take any action, including making the object available to other threads again, but the primary purpose of finalize is to perform a purge before the object is discarded irrevocably. For example, the Finalize method of an object representing an input/output connection can perform an explicit I/O transaction so that the connection is interrupted before the object is permanently discarded.


The Finalize method of the Object class performs a non-specific operation; It performs only a few general returns. Subclasses of Object can override this definition.


The Java programming language does not guarantee which thread will invoke the Finalize method for a given object. However, it is guaranteed that when finalize is called, the thread that called Finalize will not hold any user-visible synchronization locks. If the Finalize method throws an uncaught exception, the exception is ignored, and the object's finalization operation terminates.


After you enable the Finalize method for an object, no further action is taken until the Java virtual machine determines again that any thread that has not been terminated can no longer access the object by any means, including possible operations performed by other objects or classes that are ready to terminate, and the object may be discarded when the operation is performed.


For any given object, the Java virtual machine calls only one Finalize method at most.


Any exception thrown by the Finalize method will cause the end operation of this object to stop, but it can be ignored by other methods .

In-depth study of Java.lang.Object class

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.