Java foundation | Object source code parsing

Object source code parsing

Java is an object-oriented language, Java in which everything can be seen as an object, and Java which all objects are by default inherited from the Object class, so the dog brother again today to review the class.

Object methods Overview

Object inner seen on FIG. 12, a total process wherein RegisterNatives () is implemented in C language, outside the scope of this.

1、getClass

/**
     * Returns the runtime class of this {@code Object}. The returned
     * {@code Class} object is the object that is locked by {@code
     * static synchronized} methods of the represented class.
*/
public final native Class<?> getClass();
复制代码

The role of this method is to return the runtime class of an object, its return value is of type Class, Class c = obj.getClass (); method by all members of the object c, we can get the object, each member methods is a Method object; we can also get all of the object's member variables, member variables are each a Field object; Similarly, we can also obtain the object's constructor, the constructor is a constructor object. This method will be used to the reflection.

2、hashCode

/**
     * Returns a hash code value for the object. This method is
     * supported for the benefit of hash tables such as those provided by
     * {@link java.util.HashMap}.
*/
    public native int hashCode();
复制代码

Notes This method is relatively long, hold out. Notes that:

  • hashCode method returns the hash value.
  • The return value is the default address of the object converted from.
  • HashCode the same object calls the return value is equal.
  • Two objects of equal equals, hashCode it must be equal.
  • It equals two objects are not equal, then hashCode is not necessarily equal.

3、equals

public boolean equals(Object obj) {
    return (this == obj);
}
复制代码

equals the implementation is very simple, its role is to compare two objects are equal, and the comparison is based on both the memory address. In addition, it equals also follow the following principles:

1、自反性:x.equals(x);  // true
2、对称性:x.equals(y) == y.equals(x);  // true
3、传递性:if (x.equals(y) && y.equals(z))
            x.equals(z); // true;

4、一致性,只要对象没有被修改,多次调用 equals() 方法结果不变:
x.equals(y) == x.equals(y); // true 

5、非空性,对任何不是 null 的对象 x 调用 x.equals(null) 结果都为 false :
x.equals(null); // false;
复制代码

Why rewrite hashcode and equals?

Share this question before the text is too old: mp.weixin.qq.com/s/iIoAnneae...

4、clone

protected native Object clone() throws CloneNotSupportedException;
复制代码

clone () method Object is protected, it is not public, a class not explicitly to override clone (), directly to the other classes can not call clone instances of the class () method. In addition, Clone comments also mentioned the more important points:

  • Object cloning must implement the Cloneable interface and override the clone method, otherwise it will report a CloneNotSupportedException
  • clone () method is not a method Cloneable interface, but a protected method Object. Cloneable interface only provides that if a class does not implement the Cloneable interface and calls the clone () method will throw CloneNotSupportedException.
  • Shallow copy: the original object and the copy object reference type reference the same object.
  • Deep copy: the original object and the copy object reference type refer to different objects.

Comments on shallow copy and deep copy, look at this old article: mp.weixin.qq.com/s/I6Gq1shyf...

5、toString

public String toString() {
       return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
复制代码

This method should be nothing to talk about, native toString method simply returns the object name + its hashCode, but did develop all know, is not the role of native toString. We need to override toString generally because it's easy to debug, need to know the object's property value, rather than just hashCode. Therefore, it should be rewritten like this:

public class Student {

    private int age;

    private String name;

    // 省略 get、set

    @Override
    public String toString() {
        return "Student{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }
}
复制代码

6, notify and wait

public final native void notify();
public final native void notifyAll();
复制代码

First, notify, the comment is not posted, the effect is random notify wake up a thread waiting in the queue, and notifyAll wakes up all the threads is waiting queue.

public final void wait() throws InterruptedException {
     wait(0);
}

public final native void wait(long timeout) throws InterruptedException;

public final void wait(long timeout, int nanos) throws InterruptedException {
        if (timeout < 0) {
            throw new IllegalArgumentException("timeout value is negative");
        }

        if (nanos < 0 || nanos > 999999) {
            throw new IllegalArgumentException(
                                "nanosecond timeout value out of range");
        }

        if (nanos > 0) {
            timeout++;
        }

        wait(timeout);
}
复制代码

Then wait, wait effect is to make the current thread into a wait state, at the same time, wait () also makes the current thread releases the lock it holds. Until another thread invokes the object's notify () method or the notifyAll () method, the current thread wakes up into the ready state.

() Method or the notifyAll () method, or a specified amount of time the wait (long timeout) (in milliseconds) so that the current thread is waiting (blocked) state until another thread invokes the object's notify, the current thread is waked up ready state.

wait (long timeout, int nanos) and wait (long timeout) function the same, the only difference is that this can provide higher accuracy. The total delay time (in nanoseconds) is calculated as 1000000 * timeout + nanos. By the way, wait (0,0), and wait (0) the same effect.

In addition, comments notify and wait in there so:

* <p>
     * This method should only be called by a thread that is the owner
     * of this object's monitor. A thread becomes the owner of the
     * object's monitor in one of three ways:
     * <ul>
     * <li>By executing a synchronized instance method of that object.
     * <li>By executing the body of a {@code synchronized} statement
     *     that synchronizes on the object.
     * <li>For objects of type {@code Class,} by executing a
     *     synchronized static method of that class.
     * </ul>
* <p>
复制代码

See this in English, just over four, I shiver. Notes above mainly describes the use of standardized notify and wait approach. This means that the two must be synchronized using a modified method of synchronization or synchronization code.

  • Why wait () must be synchronous (Synchronized) method / code block calls?

A: Call wait () is to release the lock, release the lock on the premise that must first obtain a lock, to get the lock to release the lock.

  • Why notify (), notifyAll () must be synchronous (Synchronized) method / code block calls?

A: notify (), notifyAll () is to contain the lock wait () method of the thread, let it continue to go on, if there is no lock itself, how to call other threads to lock it? (Essentially a thread to lock in competitive entrance queues)

Details, refer to this blog post: blog.csdn.net/qq_42145871...

  • Thread.sleep () and Object.wait () What is the difference?

First of all, both of which can suspend the current thread, freeing the CPU to control. The main difference is that the Object.wait () at the same time releasing CPU, object lock release control. The Thread.sleep () does not release the lock. In other words sleep is bullying, dog in the manger.

Recommended reading:

1, java | what is a dynamic agency

2, SpringBoot | start principle

3, SpringBoot | automatic configuration principle

A good basket

Guess you like

Origin juejin.im/post/5d4eaccee51d4561c541a679