Java source object class __java

Source: Internet
Author: User
Tags static class thread class throwable
  IntelliJ API decompiler stub source generated from a class file//implementation of methods are not available pack

Age Java.lang;

    Public class Object {public object () {/* Compiled code */} private static native void Registernatives ();

    Public final native java.lang.class<?> GetClass ();

    public native int hashcode (); public boolean equals (Java.lang.Object o) {/* Compiled code */} protected Native Java.lang.Object clone () throws Ja

    Va.lang.CloneNotSupportedException;

    Public java.lang.String toString () {/* Compiled code */} public final native void Notify ();

    Public final native void Notifyall ();

    Public final native void wait (long L) throws java.lang.InterruptedException;  Public final void Wait (long l, int i) throws java.lang.InterruptedException {/* Compiled code */} public final void Wait () throws Java.lang.InterruptedException {/* Compiled code */} protected void Finalize () throws Java.lang.Thro wable { /* Compiled code */}} 
Object is the ultimate class of all Java classes, our common custom class but does not inherit object (Java compiler automatically introduced, if manually inherited object, there is no problem, Java single inheritance has some limitations)
    public static class User {
        @Override
        protected Object Clone () throws Clonenotsupportedexception {
            return Super.clone ();
        }

        @Override public
        int hashcode () {return
            super.hashcode ();
        }
    }


The object class is about 12 methods, and the following one by one explains the effects of these methods

1. GetClass ()

  Public final class<?> GetClass () {return
      shadow$_klass_;
    }
Returns the Run-time class for this object
The type of the actual result is class<? Extends | X|> of which | X| is called on a static type whose expression is erased getclass. For example, you do not need to convert in this code fragment:
Number n = 0;
class<? Extends number> C = N.getclass ();

2. Hashcode ()

   /* @return  a hash code value for this object.
     * @see     java.lang.object#equals (java.lang.Object)
     * @see     java.lang.system#identityhashcode * *
     public
    int Hashcode () {return
        identityhashcode (this);
    }
Returns the hash value of the object, which is supported for a hash table, such as HashMap
Hashcode is characterized by:
1. As long as the method is invoked on the same object multiple times while executing the Java application, hashcode () always returns the same integer (provided that the object's information has not changed)
2. Compared to two objects, if the Equals method is used to return true, then the hashcode value of the two objects is the same

3. For two objects, if you use the Equals method to compare to false, then the hash value of the two objects does not necessarily require a different, can be the same or different, however, if different, you can improve performance
4. For the object class, the hashcode of the different object objects is different (the object's hashcode represents the storage address of the objects, but if the hash code is rewritten it does not necessarily mean that the address is stored)

3. Clone ()

    Protected Object Clone () throws Clonenotsupportedexception {
        if (!) ( This instanceof cloneable)) {
            throw new clonenotsupportedexception ("Class" + getclass (). GetName () +
                                                 "doesn ' t im Plement cloneable ");
        }

        return Internalclone ();
    }
Clone method: Creates and returns a copy of this object; For any object x x.clone ()!=x
and X.clone (). GetClass () ==x.getclass () although the base class of the object supports clone, but object itself does not implement Cloneable, the custom class needs to implement the Cloneable interface, otherwise it throws an exception 4. toString ()

Returns the string representation of an object, generally, this method returns a fixed template

Public String toString () {return
        getclass (). GetName () + "@" + integer.tohexstring (Hashcode ());
    }
This is not well reflected in actual development, so the large compilers support regenerating ToString (), such as:
public static class User {
       private String name;
       private int age;

        @Override public
        String toString () {return
            "user{" +
                    "name= '" + name + ' \ ' +
                    ", age=" + Age +
                    '} '; 
  }
    }
5. Finalize ()
/* @throws throwable the {@code Exception} raised by this method
     * @see java.lang.ref.WeakReference
     * @see java. Lang.ref.PhantomReference
     * @jls 12.6 Finalization of Class instances
    /protected void Finalize () Throws Throwable {}
The Finalize () method can be overridden by a quilt class object and, as a Terminator, completes the final cleanup work when the GC is invoked (for example, freeing system resources, and so on). This is the end. The default Finalize () method does nothing and returns directly when invoked.
For any object, its finalize () method is not executed two times by the JVM. If you want an object to be called again (for example, by assigning its reference to a static variable), note that the Finalize () method will not be invoked the second time when the object has been reclaimed by GC.

Test:
Package Asange.javastudy.java.lang;

/**
 * @author Youxuan  e-mail:xuanyouwu@163.com *
 @version 2.3.1 *
 @Description
 * @date CREATETIME:2018/1/20
 *
/public class Objecttest {public

    static class User {
        private String name;
        private int age;

        @Override public
        String toString () {return
            "user{" +
                    "name= '" + name + ' \ ' +
                    ", age=" + Age +
                    " }';
        }

        @Override
        protected void Finalize () throws Throwable {
            System.out.println ("Finalize");
            Super.finalize ();
        }

    public static void Main (string[] args) throws Exception {
        user o = new user ();
        o = null;
        System.GC ();
        System.GC ();
    }


Run Result:

Asange.javastudy.java.lang.ObjectTest
Finalize

Process finished with exit code 0
You can see the result: Two GC finalize only performed one time


6. Wait () notify () Notifyall ()These three methods are about thread blocking and thread wakeup
1. Wait (), the Notify () and the Notifyall () method are local methods and are final types and cannot be overridden
2. The wait () method that invokes an object can block the current thread, and the current thread must own the monitor (that is, the lock) of the object.
3. The Notify () method that invokes an object wakes up a thread that is waiting for the monitor on this object, and if multiple threads are waiting for this monitor, wake one of the threads;
4. Call the Notifyall () method to wake up all the monitor that is waiting for this object

Why these three are not methods in the thread class declaration, but rather the methods declared in the object class (of course, because the thread class inherits the object class, thread can also invoke the three methods). In fact, this problem is very simple, because each object has monitor (that is, lock), so the current thread to wait for the lock of an object, of course, it should be done through this object. Instead of using the current thread, because the current thread might wait for a lock on multiple threads, it would be very complicated if manipulated by a thread.
As mentioned above, if the wait () method of an object is invoked, the current thread must own the monitor (that is, the lock) of the object, so invoking the wait () method must be done in either the synchronized block or the synchronization method (synchronized block or Synchronized method).
Calling the Wait () method of an object is equivalent to having the current thread hand over the monitor for this object and then into the waiting state, waiting for the subsequent lock on this object again (the Sleep method in the thread class suspends the current thread for a period of time, allowing other threads to continue executing, But it does not release object locks);
The Notify () method wakes up a thread that is waiting for monitor for the object, and when multiple threads are waiting for the object's monitor, only one of the threads is awakened, and it is not clear which thread to wake.
Similarly, the Notify () method of an object is invoked, and the current thread must also have the monitor of the object, so the call to the Notify () method must be done in either the synchronized block or the synchronization method (synchronized block or Synchronized method).

The Nofityall () method is able to wake up all threads that are waiting for monitor for the object, unlike the Notify () method.


One thing to note here is that the Notify () and Notifyall () methods simply wake up the thread of the monitor waiting for the object, and do not decide which thread will get to monitor.


As a simple example: if there are three threads Thread1, Thread2, and Thread3 waiting for the monitor of the object Objecta, THREAD4 owns the monitor for object objecta, When the Objecta.notify () method is invoked in Thread4, only one of Thread1, Thread2, and Thread3 can be awakened. Note that being awakened does not mean immediately acquiring the OBJECTA Monitor. If the Objecta.notifyall () method is invoked in Thread4, then the Thread1, Thread2, and Thread3 three threads will be awakened, The monitor on which the thread will then be able to acquire the OBJECTA relies on the operating system's schedule specifically.


In particular, it is important to note that a thread is awakened does not mean immediately acquire the object's monitor, only after the call notify () or Notifyall () and exit the synchronized block, release the object lock, the rest of the thread to get lock execution.

public class Objecttest {public static Object obj = new Object ();
        public static void Main (string[] args) throws Exception {Object O2 = new Object ();
        Thread1 thread1 = new Thread1 ();
        Thread2 thread2 = new Thread2 ();
        Thread1.start ();
    Thread2.start ();
            Static Class Thread1 extends Thread {@Override public void run () {super.run ();
            SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () + "start"); Synchronized (obj) {try {System.out.println ("thread" + thread.currentthread (). GetName ()
                    + "Call the Object.wait ()");
                Obj.wait ();
                catch (Interruptedexception e) {e.printstacktrace ();
            SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () + "Get to lock"); }} static Class Thread2 extends Thread {@Override public voidRun () {super.run ();
            SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () + "start");
                Synchronized (obj) {obj.notify ();
            SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () + "called Object.notify ()");
        } System.out.println ("Thread" + thread.currentthread (). GetName () + "release lock"); }
    }

}

Run Result:

Thread Thread-0 start thread
Thread-1 start
thread Thread-0 called object.wait ()
thread Thread-1 called object.notify ()
Thread Thread-1 freed the lock
thread Thread-0 acquired the lock

Process finished with exit code 0


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.