Java Basics Summary (i) Create and destroy objects __java

Source: Internet
Author: User
Tags garbage collection int size memory usage protected constructor

Chizi: Next year will leave school to find work, time is really fast, think a few years, do some things, there are some things do not do well, have a lot of harvest, there are many regrets. Emotional words in this should not be said, since the choice of the programmer this road, but also to do it to the cause of the attitude. There are a few months before the formal job search, do things, try new technology is very cool, but the foundation is also very important, in this short few months time, I will have learned some knowledge, Java, data structure, algorithm, network, OS&LINUX,J2EE and so on knowledge to check gaps, A good comb, not only to find a job, but also a must adhere to the attitude.

For the collation of Java knowledge, based on the "Effetive Java" 2nd and "Java programming thought" 4th supplemented by the JVM and design patterns of knowledge, combined with the knowledge of books and my understanding of the collation. OK, start one of my articles--Create and destroy objects.


1. Constructors in Java:

A constructor is a special type of method that has the same name as a class, has no return type, and a combination of the new keyword to return a reference to an object instance. Tij says it's a static method, but with bytecode we can see that there is no static keyword, and its behavior is different from other static methods (you can access non-static member variables), so this is not entirely accurate, and there is no further scrutiny. 1.1 Definition Builder:

A class can have multiple constructors, and if you do not define a constructor, the Java compiler will first add a default constructor at the stage of semantic parsing.

Multiple constructors can be implemented through method overloading (overload), noting that only the same method name and different argument lists can distinguish between overloaded versions, and the return type cannot be distinguished .

In particular, when using basic type parameter overloading, be aware of automatic conversions of types such as (char->int, small, large) and narrowing conversions (coercion type conversions, large and small), and of course using the most matched types. 1.2 this keyword:

Through this pointer we can access the class's instance variables and methods, but it is best to use it if necessary (return or use the instance, the inner class accesses the instance variable method with the same name as the constructor settings property, etc.), otherwise you do not have to add it, and the compilation will also help you add it

When there are multiple overloaded versions of constructors, we can use this to invoke other constructors within the constructor to avoid some duplicate code:

    Public constructortest (int a) {
        this.a = A;
    }

    Public constructortest (int A, String s) {This
        (a);
        THIS.S = s;
    }

PS: Overlapping constructors are an option when there are many parameters in the constructor, but the better approach is to use the builder pattern, which is described later. 1.3 Static Keyword:

static (Static), static methods, and static variables are class methods and class variables that cannot use the this reference and are placed in the method area for each thread to share. The static variable initializes and static initializes it, and executes once after the class is loaded (implicitly loading or displaying the load).


2. Cleanup, end object (Finalize)/garbage collection (CG):This involves a lot of content. Java provides a garbage collector, but memory leaks can occur in a very subtle way (using an array of references), while some of the resources that might be used in an object must be released when the object is no longer in use (Connection,fileinputstream, etc.).
First, the object instance is stored in the Java heap as a copy of the class, in the JVM, the accessibility analysis is generally used for garbage collection, that is, if you follow the reference, the "live" object should be able to reach the CG Root (including, static variables, constant references, the local variables table in the stack and the local method stack Jni The reference in the native method). The garbage collector marks unreachable objects and reclaims them in different areas of the heap using different methods.
Mark-Clear: If there is very little rubbish, it is quick and simple, but if there is a lot of rubbish, it will produce a lot of debris;Copy: We can divide the memory areas that need to be garbage collected into 2 parts, for example, A and B, when CG is needed, copy A's surviving object directly to B (previously empty), and empty A is OK, no need to consider the problem of fragmentation, in fact, in the JVM (Hotspot) divided into 3 parts, The general scale can be 8:1:1, they are named Eden,surivor1,surivor2, because the statistics Java program in more than 95% of the objects are soon no longer used, so Eden is very large, surivor can be small (fewer surviving objects). This is actually much more used with the new generation of garbage collection.Mark-Finishing: There is a new generation of course there are old times, and the new generation of different, the old age of the object of relatively stable, garbage collection is very few, after all, after the minor CG baptism will not be so easy to hang off, a joke. Mark-the difference between sorting and clearing is that it is not directly removed from the original position, but instead moves the surviving object to one end and then immediately clears the missing object together. Because we also say that the old age of the object of less recycling, so the movement is relatively small. So there won't be a lot of debris.
So we can see that the JVM uses the method of generational recycling to divide and conquer different situations.
What is the relationship between the release of resources, termination, and garbage collection:First of allgarbage collection is only related to memory usage, CG is performed when there is not enough memory (or if we are satisfied with the conditions we set). When was finalize (), for those unreachable objects, until they were really recycledat least two mark stages required: (1) First filter those objects that do not need to execute the Finalize method, without override the Finalize method and objects that have executed the Finalize method, they can be "dead", and for finalize objects that have not yet been executed, They enter the F-queue queue, which is equivalent to a "death sentence" and a chance; (2) F-queue queue, there is a finalization thread that specifically invokes these objects (so the Finalize method is a callback method), If there is an association with the CG roots in the Finalize method, OK, it is alive, otherwise "die".
Therefore, we seeThe Finalize method relies directly on garbage collection and end threads, and the end thread has a low priority, which means it may not be implemented for a long time, and garbage collection is something you can't control directly (System.GC and system.runfinalize are also looking at the JVM's face), sodestructors in Finalize and C + + are not the same thing
For database connections, file access handles, and so on, objects that occupy database resources and system resources,we must release/close them in time.。 You can define a close method to ensure that the necessary shutdown is performed in the try-finally, and even closable interfaces, fileinputstream,connection, etc. are implemented in Java.
What is the use of Finalize method:(1) You can check that the Close method has been executed in the Finalize method, and this is a security-sensitive practice that Fileinputstream,connection,timer does. (2) When using JNI, if you want to release sensitive resources from the local object, you need to display the override Finalize method to release it. (3) You can save yourself in the Finalize method.
If you want to use it, note that in the inheritance system, it is the same as the constructor method that we maintain the "Terminate method chain" manually.In General, try not to use the Finalize method.
3. Initialization:

If you want to really figure out object initialization rather than just remembering rules like the initial value of a member variable, I think it's worth knowing how a class can be programmed from bytecode when it first creates an object.

When using a class for the first time, whether the display loads a class (class.forname, etc.) or implicitly loads a class (A.staticvariable,new a ()), the first thing to do is to have the ClassLoader loaded:

(1) ClassLoader first through the class name positioning to the location of the class file (through the classpath, etc.), the byte code loaded into memory, through the preparation, bytecode verification and resolve and other links will wait for a class object, put into the method area;

(2) After this is class initialization, which is the static variables in the class and the static initializers will be initialized in the order of location, static variables are also placed in the method area;

(3) If you are creating an instance, the next task is to allocate memory on the heap, the specific method may have pointer collision and idle list;

(4) When the memory space is obtained, all zeros are first set, which is why the member variables of the class have the initial value, and then if the initialization value is specified, the same is done in sequence.

(5) At the end of the execution <init> that is our definition of the constructor used to carry out our custom initialization process, we can get the reference to the object instance we want.

So in the class, the initialization order of each part is: static variable, static initializer (by position order)--> non-static member variable (by position order)--> constructor ;

Having said the basic process, let's take a look at how some of the specific types in Java are initialized.


3.1 Array initialization: An array is also an object in Java, but it is not instantiated by a class, it is created directly by the JVM, and its parent class is object, so you can use the method of object on the array. First, review the basic syntax: through the array initializer: int[] a = {12,3}; Create dynamically via NEW: int[] A = new int[5];
For garbage collection, arrays are also a special type, looking at the following example:

public class Mstack {
    private static final int default_size =;
    Private object[] elements = new Object[default_size];
    private int size = 0;

    Public Mstack () {
        elements = new object[default_size];
    }

    public void push (Object element) {
        ensurecapacity ();
        elements[size++] = element;
    }

    Public Object pop () {
        if (size = = 0) {
            throw new RuntimeException ("Empty stack cannot pop");
        }
        return elements[--size];
    }

    public void Ensurecapacity () {
        if (size = = elements.length) {
            elements = arrays.copyof (elements, 2 * size + 1); 
  }}}


This is an example of "effective Java", in which the stack does not place a reference to null that is already out of the stack in the case of POPs; These references are "expired references," which, although not used, But it will be copied to a larger array along with the Arrays.copy, which is also a surviving object for the JVM, but useless for our applications. In a service that needs to run for a long time, if such a problem occurs, it can easily lead to oom.
3.2 Variable parameter list: The JDK1.5 feature, which is closely related to the array. In fact, the variable argument list actually passes a set of parameters through an array, which I think can be considered a syntactic candy. When you use a variable parameter list, if you have more than one overloaded version, you perform the most matching version based on the type of argument you pass, but you need to be aware of some situations where a "conflict" occurs:
public class Varargsinit {
    //overload with var argument public
    static void F (long...longs) {
        System.out.println ("F_long_varargs");
    }

    public static void F (character...characters) {
        System.out.println ("F_character_varargs");
    }

    public static void F (float F, character...characters) {
        System.out.println ("F_float_character_varargs");
    }

    public static void G (float F, character...characters) {
        System.out.println ("G_float_character_varargs");
    } Public

    static void G (char C, character...characters) {
        System.out.println ("G_char_character_varargs");
    } Public

    static void Main (string[] args) {
//        f ();//error: (9) Java:reference to F is ambiguous
//        f ();
        F (1, ' a '); OK
//        F (' A ', ' B ');//error: (9) Java:reference to F is ambiguous
        g (' A ', ' B ');//ok
    }

In this case, F (' A ', ' B ') causes compilation errors because it matches both the 3rd and 2nd F () versions (because ' a ' can be converted to float), and the workaround, which is simple in the two versions of the G method, does not conflict.
3.3 enumerations:JDK1.5 add attribute. An enum is also a class that derives from an enum abstract class, but unlike a normal class, the compiler adds some attributes to it, and I think it's possible to think of an enum as a class with a special function: Let's take a look at the byte code of an enumerated type:
Final enum Hr.test.Color {//All enumerated values are class static constants  public static final enum Hr.test.Color RED;  public Static FINA
 l enum Hr.test.Color BLUE;
 public static final enum Hr.test.Color black;
 public static final enum Hr.test.Color yellow;
 
public static final enum Hr.test.Color GREEN;
  
  private static final synthetic hr.test.color[] enum$values; Initializes the first initialization of all enumerated value objects for an enumerated class  static {0 New Hr.test.Color [1] 3 DUP 4 LDC <string "RED" &G T [16]///Put the enumeration value string "RED" into the operand stack 6 iconst_0///Put the integer value of 0 into the operand stack 7 invokespecial hr.test.Color (java.lang.String, int) [1
      7]//Call the private constructor of the color class to create a Color object red putstatic hr.test.Color.RED:hr.test.Color [21]///Assign the enumeration object to the static constant RED of color.  .........
  
  Enumerate objects blue and so on with the same 102 return};
 Private constructors, it is not possible to dynamically create an enumeration class object externally (that is, it is not possible to dynamically create an enumeration value). Private Color (java.lang.String arg0, int arg1) {//protected constructor that invokes the parent class enum creates an enumeration object 3 Invokespecial Java.lang.Enum (java. Lang.
String, int) [38]};   public static Hr.test.ColOr[] VALUES ();
public static Hr.test.Color valueof (java.lang.String arg0); }
From bytecode parsing, you can first see: (1) It is final, so we cannot inherit it; (2) All enumerated values are instances of color, all of which are public and final; we also see that the compiler added 3 methods to the enum: (1) A private constructor, which guarantees that an enumeration object of that type cannot be created dynamically, and we cannot create an instance of an enum type using reflection:
Public enum  Menum {
    E1;

    Static Class A {
        private a () {
        }
    } public

    static void Main (string[] args) throws Exception {
        class< A> a = A.class;
        Constructor constructor = A.getdeclaredconstructor ();
        Constructor.setaccessible (true);
        Constructor.newinstance ();
        class<?> EC = Menum.class;
        Constructor Constructor1 = Ec.getdeclaredconstructor (String.class, int.class);
        Constructor1.setaccessible (true);
        Constructor1.newinstance ("YJH", 2);
    }

}
Result: Class A can be created normally, and the enum type, Java.lang.IllegalArgumentException:Cannot reflectively create enum objects, Because there are such checks in the class.newinstance:
if ((Clazz.getmodifiers () & Modifier.enum)!= 0)
            throw new IllegalArgumentException ("Cannot reflectively create Enum objects ");
(2) Values static methods; (3) valueof (String) static methods: They are all added by the compiler for the specific enum type, and you do not see them in the Enum abstract class;
An enum can be said to be a strictly global, immutable security type that can also be safely serialized without fear of a unique situation, and because of this, using a single element enumeration to create a single Instance object is an excellent way to do without worrying about reflection attacks.
Ps:enum can be used in conjunction with switch, very convenient;
4. Practice of creating and destroying objects:"Effetive Java" for this piece gives some excellent advice, after each end of each article I will attach a good practice model and to pay attention to the reverse mode. Learning these ideas and design patterns is a great benefit to me in using and understanding frameworks such as different modules in Java and Spring, because they are all built on the ideas and patterns that help me better understand their structure and capabilities. 4.1 Using the static factory method instead of the constructor:Advantages: (1) in a constructor with more complex parameters, this is difficult to distinguish between the functional differences by overloaded versions, and static factory methods can be named according to functionality, as is the case with a thread pool that creates different functions in executors, and static factory methods obscure the complexity of the constructor; (2) You do not have to create a new object every time you call them, static factory methods can be used for Singleton, class,final, immutable classes (final field), not instantiated classes (private constructor) these different scenes; (3) Return any subtypes of the original return type: This effect feels far-reaching, broad, first of all, in the collection package there are collection,list,set,map,iterator interfaces, collections tool classes, Provides many collection class implementations with additional functionality, all of which are nested classes defined in collections, returned through static factory methods, and iterator, also based on internal classes, that are returned through the static factory methods can hide specific implementations and support interface-oriented programming。 In the development of the Java EE Project, often used in the persistence Api,websocket Api,servlet API, and so on, they are part of the specification, we only reference the API, interface, and the specific implementation we can use the Hibernate , spring's subprojects, like the servlet and Websokcet APIs, implement them more specifically by the Java application Server, and the tomcat8.0 also provides websocket implementations. This is " Services Provider Framework (Service provider framework)", provided by the provider Service InterfaceImplementation, the provider can use the Provider Registration InterfaceRegister yourself and the provider can also implement Provider Interfaceor through the class name directly registered, the client user through the Service Access Interface(In fact, the static Factory method); (4) The object was created when the generic parameter was used to simplify, but with the Diomand expression, Java can deduce the type itself;
use builder mode for more than 4.2 constructor parameters:Overlapping constructors and Bean+setter are really hard to maintain, and as you know, the builder model is not just a flexible set of parameters; You can also create immutable objects.
Public final class Hasbuilder {
    private final int i1;
    private final int i2;
    Private final String S1;

    Public Hasbuilder (Builder Builder) {
        this.i1 = builder.i1;
        This.i2 = Builder.i2;
        THIS.S1 = builder.s1;
    }

    public static class Builder {
        private int i1;
        private int i2;
        Private String S1;

        Public Builder i1 (int i1) {
            this.i1 = I1;
            return this;
        }
        Public Builder i2 (int i2) {
            this.i2 = i2;
            return this;
        }
        Public Builder S1 (String s1) {
            this.s1 = S1;
            return this;
        }

        Public Hasbuilder builds () {return
            new Hasbuilder (This);}}

You can do a constraint check by building a build in a specific set value method.
4.3 to establish the appropriate single case:To sum up roughly, there are 5 different single case modes: (1) a Hungry man mode; (2) Lazy mode: Delay loading, which involves the problem of thread safety, the efficiency of using synchronized method is too low; (3) Single case based on double check Lock: JDK1.5 is safe, need to be volitale to ensure visibility, must have the ability to write it。 (4) based on static internal classes: Let the static inner class hold a static final instance, because it is the inner class, so it can be delayed loading;
public class Singletonwithinnerclass {
    private singletonwithinnerclass () {
        System.out.println ("initialized") );
    }

    private static class Singletonholder {
        private static final singletonwithinnerclass s = new Singletonwithinnerclass () ;
    }

    public static Singletonwithinnerclass getinstance () {return
        singletonholder.s;
    }

    public static void Main (string[] args {
        Class c = singletonwithinnerclass.class;//not initialized
        here SYSTEM.OUT.PRINTLN ("Start initialization:");
        Singletonwithinnerclass Singletonwithinnerclass = Singletonwithinnerclass.getinstance ();

    }
}
The output of this code: start initialization:
Initialized
Visible is deferred loading, (5) Single element enumeration method, discussed above, the best, free serialization, to prevent reflection attacks;
4.4 Private constructors Prevent instantiation :For some tool classes or hosting global variables, the private constructor is used to prevent inheritance/instantiation, which is an inverse pattern if implemented using interfaces and abstract classes;
4.5 Avoid creating unnecessary objects:(1) Note that a string is a constant pool, which is actually stored through private final char[], so it is immutable and enters the constant pool only the first time a combination of this string is used: new String ("abc"); There are actually two string objects , "ABC" is a compile-time existence, it has entered the constant pool, (2) for the calendar such an instantiation of the more expensive objects to consider as much as possible reuse, (3) Use of automatic boxing type must be particularly careful to avoid in the loop because of automatic boxing and create a large number of objects, can use the basic types do not use boxing type; (4) The cost of creating and destroying small objects is very small, so it is important to consider whether it is worthwhile to use object pooling, which can also result in memory leaks.
4.6 Eliminate expired references:(1) When managing the memory itself: previously mentioned mystack (outside of their own management memory), there are two scenarios that can easily lead to memory leaks: (2) Caching: Do not allow cached references to be the only reason to prevent garbage collection, use Weakhashmap as much as possible, and it will not affect references. Of course, it needs to be noted that only the lifecycle of a cached item depends on its external reference; Check when using a background thread timer or Scheduledtreadpoolexecutor or add a new entry (Linkedhashmap provides such a mechanism); (3) Callback: This type of observer mode requires a listener or callback to register, So it's a good idea to use weak references if releasing is no longer appropriate; in fact, look at the reason for the memory leak directly is the improper management of the reference pool, at this time by the JVM accessibility analysis mechanism decided;


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.