How to correctly create and destroy Java objects __java

Source: Internet
Author: User
Tags int size map class reflection serialization static class

Java is a powerful high-level language. After learning its basic knowledge, we still need to understand its profound connotation. Next, we will take "effective Java" As a Java Advanced Learning carrier, a system of Java, a new understanding. Next, let us feel the profound meaning of Java. Chapter One: Creating and destroying Objects 1th: Consider using a static factory method instead of a builder

For a class, the most common method for a client to get an instance of itself is to provide a public constructor. However, there is a good way (it should be in every Programmer's toolbox), that is, the class provides a commonStatic Workshop Method。 (a static method that returns an instance of the class,and different from the factory method pattern in design pattern
Provides a static factory method instead of a public constructor that has the following largeAdvantages
  
   1. The static factory method has a name and the constructor does not have its own name.
If the constructor's argument itself does not exactly describe the object being returned, then there is the embarrassing situation where the customer is unable to determine what is being received. Give me a chestnut: the BigInteger that the constructor BigInteger (int,int,random) returns may be prime, and it is clearer if it is represented by a static factory method named Biginteger,probableprime. (The 1.4 release finally added this method.) )
There is also a situation where the need to build a constructor is not enough to use, we tend to provide two constructors, which is a very bad way, because the customer simply do not know which constructor to use, when the wrong constructor calls, the data error occurs. Therefore, you can use static factory methods and select names that can highlight their effects for static factory methods.
   
   2. You don't have to create a new object multiple times
Such immutable classes can use pre-built instances or cache the built instances for reuse, thereby avoiding the creation of unnecessary duplicate objects. Give me a chestnut: boolean.valueof (Boolean). It never creates an object.
In addition, there is a small advantage. Static factory methods can return the same objects for repeated calls, and can strictly control the existence of instances
   
   3. An object that can return any subtype of the original return type
When using a static factory method, the client is required to refer to the returned object through an interface instead of referencing the returned object through its implementation class. Clients never need to care about the class of objects they get from the factory method, just care about a subclass of a class.
   
   4. Create a parameterized type instance to make your code more concise
In the callParameterized Class Builder, it must be declared even if the type parameter is obvious.
Take the example of creating a map class:

Map<string,list<string>> m=new hashmap<string,list<string>> ();

When the parameters are few, it becomes extremely painful as the type parameter becomes longer. Static factory methods can solve this problem (type deduction)

public static <K,V> hashmap<k,v> newinstance () {return
        new hashmap<k,v> ();
}
Call
map<string,list<string>> m =hashmap.newinstance ();
Java1.6 does not yet have this factory method, but you can put this method in your tool class.

Disadvantages of static factory methods:
  
1. Classes cannot be quilt-class if they do not contain public or protected constructors
  
2. It does not actually differ from other static methods
No difference means anything. That is, for a class that provides a static factory method rather than a constructor, it is not explicitly identified in the API document as a constructor, so it is difficult to find out how to instantiate a class. What should we do then? There is still a way, you can focus on the static factory in class or interface annotations, and follow the standard naming conventions. 2nd: Consider using builders when encountering multiple constructor parameters

Static factory classes are mentioned above, and static factory classes are quite a lot better than constructors, but they have a common limitation: they don't extend well to a lot of optional parameters.
Workaround:
  
1, we generally think of is the use of overlapping constructor mode (can own Baidu)

Demo calling code
nutritionfacts cocacola=new nutritionfacts (240,15,6,7,0,5,6);

Overlapping constructor patterns make client code difficult to write and difficult to read when there are many parameters
  
  
2, JavaBean mode

Demo calling code
nutritionfacts cocacola=new nutritionfacts ();
Cocacola.setservingsize ();
Cocacola.setservings (8);
Cocacola.setcalories (100);

The JavaBean model also has serious drawbacks. Because the construction process is divided into several calls, the JavaBean consistency is not guaranteed in the construction process. Using objects in an inconsistent state can cause failures and is difficult to debug. In addition, the JavaBean mode prevents the class from being made impossible, so we need to take the effort to ensure its thread safety. (Manually "freeze" objects) but the manual approach is clumsy and rarely used in practice.
  
Fortunately, there is a third way.
3, builder mode
Principle: Instead of directly generating the desired object, the client invokes the constructor (or static factory) with all the necessary parameters to get a builder object. The client then invokes a setter-like method on the Builder object, setting each relevant optional parameter. Finally, the parameterless build method is invoked to generate an immutable object. Make up for the deficiencies of the first two methods.
The code is as follows:

public class nutritionfacts{private final int servingsize;
    private final int servings;
    private final int fat;
        public static class builder{//required parameters private final int servingsize;


        private final int servings;
        private int fat=0;
            Public Builder (int servingsize,int servings) {this.servingsize=servingsize;
        This.servings=servings;
            Public Builder fat (int val) {fat=val;
        return this;
        Public nutritionfacts Builder () {Return to New nutritionfacts (this);
        } private Nutritionfacts (Builder Builder) {servingsize=builder.servingsize;
        Servings=builder.servings;
    Fat=builder.fat;
The experiment call code nutritionfacts cocacola=new Nutritionfacts.builder (200,8). Fat. Builder (); Create Success 

The advantage of builder in comparison to the constructor is that it can have multiple variable (varargs) parameters. The constructor can have only one variable parameter. And because builder use a separate method to set each parameter, how many will have, how to adjust the adjustment.
In summary, if a class constructor or static factory has more than 4 parameters, this class is designed with the preferred builder mode, especially when most of the parameters are optional.
   3rd: Harden the Singleton property with a private constructor or enum type

   
Singleton refers to a class that is instantiated only once. Typically represents a system component that is inherently unique, such as a window manager or a file system ( making a class singleton makes it difficult for its client testing because the singleton cannot be replaced by a mock implementation unless it implements an interface that acts as its type )
There are two ways to implement Singleton before Java1.5 is released.

The first type: public static member is final domain

public class lin{public
    static final Lin INSTANCE =new Lin ()//using final modification, clearly demonstrates that this class is a single example
    private Lin () {...}
    public void leavethebuilding () {...}}

Because of the lack of public or protected constructors, Lin's global uniqueness is ensured: Once the Lin class is instantiated, there will only be a Lin instance, and no behavior from the client will change that. note, however, that privileged clients can invoke the private constructor through the Accessibleobject.setaccessible method, using the reflection mechanism. (to protect against this attack, you can modify the constructor to throw an exception when you want to create the second instance)

The second type: Public members are static methods

public class lin{
    private static final Lin INSTANCE = new Lin ();
    Private Lin () {...}
    public static Lin getinstance () {return INSTANCE;}

    public void leavethebuilding () {...}}

The same object reference is returned for all calls, so there is only one Lin instance to be guaranteed.
  
Both of these methods keep the constructor private and export the public static member variable to allow the client access to a unique instance of the class

Today, however, the above public domain approach does not have an advantage in performance, as the current JVM implementation can almost inline the invocation of static factory methods. (is not very rush, talk about so long Bo Lord you tell me that the above method no longer has the advantage, that has eggs. Do not worry ~ always have to know its connotation before you can really understand the principle of its efficient operation. The next step is to introduce the best way to implement Singleton .

Third: Write an enumeration type that contains a single element

public enum lin{
    INSTANCE;

    public void leavethebuilding () {...}

The serialization mechanism is provided free of charge, even when confronted with complex serialization or reflection mechanisms, and can be absolutely prevented from instantiating multiple times. 4th: Enhancing the ability of an instance through a private constructor

public class utilityclass{
private Utilityclass () {
    throw new Assertionerror ();
    //remainder Omitted
    

This idiom has a little side effect, it makes a class cannot quilt class. Subclass there is no accessible superclass constructor to invoke 5th: Avoid creating unnecessary objects

Partner. It is best to always accompany the same one, rather than in the lonely when the gun to find objects. Objects, too, are better able to be reused, rather than creating a new object with the same functionality every time you need it.

If the object is immutable, it can always be reused.

Don ' t do this!

String S=new string ("new");

So if you loop, you create countless instances of unnecessary

Open the way correctly

String s= "Reuse";

can also be reused for mutable objects that are known not to be modified

Class person{
    Private final date birthdate;//was born, so you cannot modify the

    private static final date boom_start;// The final proof has been
    established as a constant for the private static final Date boom_end;//

    the same as the static{//initialization, and is therefore immutable class
      calender gmtcal= Calender. getinstance (Timezone.gettimezone ("GMT"));
      Gmtcal.set (1946,calendar.january,1,0,0,0);
      Boom_start=gmtcal.gettime ();
      Gmtcal.set (1965,calendar.january,1,0,0,0);
      Boom_end=gmtcal.gettime ();
    }

    public Boolean Isbabyboomer () {
        return  Birthdate.compareto (Boom_start) >= 0 &&
                Birthdate.compareto (Boom_end) < 0;
    }
}

The above method is much faster when invoked at multiple times (because it is already reused for creating something good).

Through this point of judgment, we know the importance of the correct use of the object. With the above method of reuse, some people may think of object pooling. Are these objects suitable for the object pool? Fact

It is not a good idea to avoid creating objects by maintaining your own object pool, unless the objects in the pool are very heavyweight. A typical object pool is a database connection pool. The cost of establishing a database connection is very high, plus the database license may limit your use of a certain number of connections, so reusing these objects is very meaningful. In general, however, maintaining your own object pool can make the code messy, increase memory footprint, and damage performance. In addition, the modern JVM implements a highly optimized garbage collector, so performance can easily exceed lightweight object pool performance. So, generally use the heavyweight object pool.
   6th: Eliminate outdated object references

  
Do you remember the title of our chapter? (There are too many static constructors in front of you, and it's estimated that everyone has forgotten the title of this chapter.) Yes, the object is created and destroyed.
  
Today, we'll talk about the elimination of expired object references.

Because Java has a powerful garbage collection function, we might think, gee, we don't need to think about memory management anymore, it's cool. But it's not. Look at the following example and you'll know.

public class stack{
    private object[] elements;
    private int Size = 0;
    private static final int default_size =;

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

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

    Public Object pop () {
        if (size==0)
            throw new = Emptystackexception ();
        return elements[--size];
    }

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

There is no obvious error in the above program, and everything works fine. But there is a problem hidden in the program: memory leaks. As the garbage collector activity increases, the memory footprint increases, the program performance will continue to reduce. In extreme cases, disk swapping or program failure may also occur.

Let's take a look at how this problem arises:
We need to know if a stack grows first and then shrinks. The objects that are popped from the stack are not, in fact, garbage-collected, even if the stack program no longer references those objects. Why, then? Because Ah, the stack internally maintains an expired reference to these objects (references that will never be lifted). Furthermore, if an object reference is unconsciously retained, the garbage collection mechanism does not process the object, nor does it handle all other objects referenced by the object. the impact on the performance of how much, think about it ...

How to solve this problem. In fact, we just need to make the following changes in the POP function

        Object result = Elements[--size];
        Elements[size] = null;
        return result;

This is called emptying expired references. Principle resolution: The elements of an array active region are already allocated, while elements of the rest of the array are free. But the garbage collector does not know this; for the garbage collector, all object references in the elements are equally valid. Only we know that the inactive part of the array is not important, so you can manually empty it.

These are a common source of memory leaks. Two other common sources of leakage are caching, monitors, and other callbacks. The workaround for both cases is to use the keys in Weakhashmap to save. Because less use, so we do not start to talk about. Have encountered is to Google again. 7th: Avoid using the finalization method

  
The first thing to emphasize is that the finalization method is often unpredictable and dangerous, and is generally not necessary. Using the finalization method can result in erratic behavior, reduced performance, and portability issues.
Second, the benefits of the End method: two legitimate uses

1, when the object owner forgot to call to display the termination method, you can act as a "safety net"

The following is the display termination method code:

Foo foo = new Foo (...);
try{...
} finally{
    foo.terminate ()//Displays the finalization method.
}

The safety net works if the client cannot invoke the above method to properly end the operation.

2, terminate the non-critical local resources

Do not use the finalization method if these are not the two uses. Reason:the Java language Specification not only guarantees that the finalization methods will be executed in a timely manner, but does not guarantee that they will be executed at all. When a program terminates, some of the finalization methods that are already inaccessible to the object are still not executed. so be careful with the end method. Summary

In this chapter, we talk about how objects are created and destroyed, when they should be used to create and destroy objects, which way is safe, and which way to avoid using ... Let's have a clearer idea of the concept of objects, because objects are the core content of Java, so how to create and destroy correctly is important.

In the next section, we will continue to learn another core of Java programming- methods .

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.