Do you really know Object Source

Welcome thumbs up reading, learning exchanges together, have questions, please leave a message.
There are also open source on GitHub JavaHouse welcome star

Introduced

Object should be a relatively simple source. Now we have to analyze him. Object is the root of the class hierarchy. Java system inside each class has a default superclass is Object. In short, all the objects, contains an array are the default method implementation of this class.

native keyword

Object class because there are many places to use the native keyword. Let's look at this guy. native keyword is an important manifestation of JNI (Java Native Interface) is. What is JNI, JNI is a mechanism other Java language (c, c ++) call. Keywords are modified native method, since the role of the statement, JVM brother told myself to call this method. Implementation of this method has been implemented in other languages ​​there, we can not see the source code.

initialization

private static native void registerNatives();
static {
    registerNatives();
}

Inside a static source block, a static method and a default constructor, not shown, no member variables. Can be seen registerNatives () method is called only once.

getClass () method

public final native Class<?> getClass();

getClass () method is modified native, tells the JVM to call their own. At the same time the final modification, it can not be overridden by subclasses. The main role is to return to the running category (Class).

hashCode () method

public native int hashCode();

getClass () method is modified native, tells the JVM to call themselves, it can be rewritten. At the same time the final modification, it can not be overridden by subclasses. The method is mainly the returned object hashCode, mainly to data structures of a hash table of services, such as HashMap.

Whether hancode closely related with the object are equal in Java. If two objects are equal, then the hashcode must be equal, but equal hashcode, two objects are not necessarily equal. If hashcode are not equal, then the two objects are not necessarily equal.

equals(Object obj)

public boolean equals(Object obj) {
    return (this == obj);
}

The method can be rewritten, primarily used to determine whether two objects are equal.

This approach has some conventions.

  1. Object any non-null object x, returns true x.equals (x).
  2. Any two non-null target objects x, y, if x.equals (y) returns true, then y.equals (x) also returns true, symmetry.
  3. Any of the three non-null target objects x, y, z, if x.equals (y) returns true, y.equals (z) returns true, then returns x.equals (z) true, transitive.
  4. Objects of any two non-empty object x, y, change what happens in writing, x.equals (y) always returns true or flase, have been sexual.
  5. Object any non-null object x, x.equals (null) return false.

Object # equals (Object obj) method, comparing the memory address, usually the practical application we want to compare the properties of two objects inside the contents are equal, it will override this method. Here we must pay attention to rewrite time equals (Object obj), but also to rewrite the hashCode () method. Because Java provides: If two objects are equal, they have equal hashcode. For example Integer of:

@Override
public boolean equals(Object obj) {
    if (obj instanceof Integer) {
        return value == ((Integer)obj).intValue();
    }
    return false;
}

@Override
public int hashCode() {
    return Integer.hashCode(value);
}

public static int hashCode(int value) {
    return value;
}

clone()

protected native Object clone() throws CloneNotSupportedException;

The method was modified native, tells the JVM to call their own. When we use the custom class method in, need to inherit a Cloneable interface, otherwise it will throw an exception can not be cloned. This method is a shallow copy, not a deep copy.

Shallow copy: the basic data types passed by value, by reference to reference data type passed as copy, this is a shallow copy.
Deep copy: the basic data types passed by value, a reference data type, create a new object, and copy its contents, this is a deep copy.

  • Using the code
@Data
public class Person extends Man implements Cloneable {
    private String name;
    private Person person;

    public static void main(String[] args) throws CloneNotSupportedException {
        Person person = new Person();
        person.setName("chen");
        Person clone = (Person)person.clone();
        System.out.println(clone.toString());
        System.out.println("person.equals(clone):"+person.equals(clone));
        System.out.println("person == clone:"+(person == clone));
        System.out.println("person.person == clone.person:"+(person.person == clone.person));
    }
  • result
Person(name=chen, person=null)
person.equals(clone):true
person == clone:false
person.person == clone.person:true

notify()、notifyAll() 和 wait()

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

notify () wake a random waiting thread, notifyAll () wake up all waiting threads. wait () method to let the current thread into a wait state.

flow chart

No matter which method to call the current thread, there is a premise: The current thread owns the object monitor. Implementation is very simple, with the synchronized keyword.

  • Implementation
synchronized (obj) {
    while (true)
        obj.wait();
        // obj.notify();          
}

As an example of practical

  • Multi-threaded print odd-even
public static void main(String[] args) {
        Thread thread = new Thread(() -> {
        for ( int i = 0; i < 100; i += 2) {
            synchronized (a) {
                System.out.println(Thread.currentThread().getName()+":"+i);
                try {
                    a.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        });
        Thread thread1 = new Thread(() -> {
            for (int i = 1; i < 100; i += 2) {
                synchronized (a) {
                    System.out.println(Thread.currentThread().getName()+":"+i);
                    a.notify();
                }
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        thread.start();thread1.start();
    }

finalize()

protected void finalize() throws Throwable { }

When the garbage collector determines there are no references to the object, this method is invoked on the object by the garbage collector. This method will only be called once.

reference

If my articles help to you, I can focus on the public micro-channel number, the first time to share your article
No public .jpg

Guess you like

Origin www.cnblogs.com/chenzhuantou/p/11978720.html