Interesting JDK, Object source code

JDK Object

Ten main methods

1、native registerNatives

A native method openJdk1.8 source code is as follows

static JNINativeMethod methods[] = {
    {"hashCode",    "()I",                    (void *)&JVM_IHashCode},
    {"wait",        "(J)V",                   (void *)&JVM_MonitorWait},
    {"notify",      "()V",                    (void *)&JVM_MonitorNotify},
    {"notifyAll",   "()V",                    (void *)&JVM_MonitorNotifyAll},
    {"clone",       "()Ljava/lang/Object;",   (void *)&JVM_Clone},
};

JNIEXPORT void JNICALL
Java_java_lang_Object_registerNatives(JNIEnv *env, jclass cls)
{
    (*env)->RegisterNatives(env, cls,
                            methods, sizeof(methods)/sizeof(methods[0]));
}

It can be understood as: it corresponds the method name of the Java layer to the local function, which is convenient for the execution engine to call the C / C ++ function according to these correspondence tables when executing the bytecode
static JNINativeMethod methods[] Function comparison table

2、native getClass

The local final method
returns the runtime class of this object, corresponding to the java.lang.Class class in java

3、equals

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

object equals, a common method is nothing special, directly compare the memory address, it is worth noting that
如果要重写equals 的话, 记得要一起重写 hashCode方法,因为要满足 equals 相等的两个对象 hashCode 值一定相等 这是来自官方的约定

4、native hashCode

 public native int hashCode();

A native method, rewriteable

5、clone()

protected native Object clone() throws CloneNotSupportedException;

Another local method, which is responsible for cloning a self and returning it to the caller. It is worth noting:

  • If the cloned class does not inherit the java.lang.Cloneable interface, a CloneNotSupportedException will be thrown.
    CloneNotSupportedException is a blank interface as follows:
    public interface Cloneable {
    }
    
    Then he has only one role, he is just a marker class used to determine whether the object can be cloned (why do the big guys who design jdk do this? Does anyone know?)
  • The clone method is only a shallow copy by default. What is a shallow copy?
    The clone method does not clone member variables within the object. To achieve deep copy, we need to rewrite the clone method ourselves

6、toString

It is also a more commonly used method. We often need to convert a class to a character form and print it out. For example, the following code System.out.println program will automatically call the toString method of Object and HashMap.
So what result will we get by executing this code?

  1 System.out.println("1:" + new Object());

  2 Map data = new HashMap<>();
  3 data.put("k", "v");
  4 System.out.println("2:" + data);

The program execution effect is as follows:

1:java.lang.Object@543e710e
2:{k=v}

We got a series of messy characters, and reasonable characters.
Because the toString source code of Object is:

    public String toString() {
        // 规则 包路径 + @ + hashcode 的十六进制字符
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }
    
    /**  
    * Integer.toHexString 将十进制转为十六进制
    * 忽略具体实现
    **/
    public static String toHexString(int i) {
      return toUnsignedString0(i, 4);
    }
    
    

8. notify () notifyAll () are all native Native method

  • The effect is similar. To wake up the thread waiting for the object to release the lock, the notifyAll method is to wake up all threads waiting for the object to release the lock
  • Calling this method without holding a lock will throw an IllegalMonitorStateException
  • Generally used with wait method
  • It is not recommended to use this series of methods in development, it will make your code very readable
  • After calling notify, the lock will not be released immediately, and execution will continue. When the lock is released after going out of the synchronization area, it will wake up the waiting thread.

9、wait() wait(long timeout) wait(long timeout, int nanos)

  • The call to the object holding the lock will immediately release the lock and immediately enter the blocking state, waiting for the notify method to wake up
  • After waking up, re-participate in the lock competition
  • wait (long timeout) The parameter of wait (long timeout, int nanos) is the timeout time. After waiting for this time, the program will automatically wake up.
    timeout (ms) nanos (subtle)
  • wait () has no parameter method, if there is no external wake-up, it will wait forever!
  • Calling this method without holding a lock will throw an IllegalMonitorStateException

10、finalize()

A very tasteless method, not recommended

protected void finalize() throws Throwable { }
  • Garbage collectorThis method is called once before recycling an object to be recycled. The premise is that this object has overridden finalize ()

what's the function?

  • Notify the program before recycling, the program can use the finalize method to recover some resources, or you can perform a self-help (do not want to be recycled)
// 拯救自己 《伪代码》
protected void finalize() throws Throwable { 
    某全局静态变量.value = this; // 自我拯救 完成,这样垃圾回收器本次将不会回收我
}
  • But be aware that the object can only be resurrected once; during the garbage collection process, Finalize cannot be called on the resurrected object. When garbage collection finds that an object to be recycled is a resurrection object, it will be directly recycled

Why not recommend it?

  • Not in time, not try finally in time, you have to wait for it to be called before garbage collection, see GC mood
  • Increase the complexity of the garbage recycling process and reduce the efficiency of the garbage collector. Heavy use may cause jvm performance issues
  • There is no guarantee of calling order, it has nothing to do with the time of death of the object
Published 17 original articles · won 24 · views 280,000 +

Guess you like

Origin blog.csdn.net/qq_22956867/article/details/89528087