Effective Java Chapter II create and Destroy objects reading notes

Source: Internet
Author: User
Tags protected constructor

Building and destroying objects
Generally there are two ways, one is to obtain an instance of itself, the most common way is to provide a common constructor. The second method is that the class can provide a common static factory method.
The static factory method differs from the constructor in three main advantages:
have a name;
Do not create new objects when they are tuned;
Returns any subtype object of the original type.
Fourth major advantage:
When you create instances of parameterized types, they make the code more concise.

Service Provider Framework
Three components:
Service Interface
Provider Hosting API
Service Access API
Optional:
Service Provider Interface

Disadvantages of the static factory approach:
If the class does not contain a common or protected constructor, it cannot be quilt-like;
They are not actually any different from other static methods;

Consider using the builder when you encounter multiple constructor parameters
Common methods: constructors for all parameters
Workaround: JavaBeans, the parameterless constructor creates the object and then calls the setter; disadvantage: validity is difficult to guarantee.
Manually freeze objects to prevent objects from being used before thawing.
The constructor mode guarantees the security of the overlapping constructor mode, and also guarantees the readability of the JavaBeans mode.

Builder Instance Build tree

In Java, the traditional abstract factory implements the class object, which acts as part of the build method with the Newinstance method. This usage implies a lot of problems. The Newinstance method always attempts to invoke the class's parameterless constructor, which may not even exist at all. If the class does not have a parameterless constructor accessible, it is not subject to a compile-time error. Instead, the customer segment code must handle instantiationexception or illegalaccessexception at run time, which is both unsightly and inconvenient. The Newinstance method also propagates any one thrown by the parameterless constructor, even if Newinstance lacks a corresponding throws sentence. In other words, Class.newinstance destroys a compile-time exception check.

Builders generally require that they be used at the outset, rather than being refactored by constructors or static factories.

Singleton refers to a class that is instantiated only once.
The first is to have the constructor private, the public static member is a final domain, the disadvantage may be reflected attack;
The second is to have the constructor private, the public member is a static factory method, no performance advantage, the advantage is flexible, and generic-related.
The third type, enumeration. Best practices. Not subject to reflection attacks, not multiple instantiation.

The ability to harden non-instancing through a private constructor. The disadvantage is that the subclass does not have an accessible superclass constructor that can be called. Because all constructors must show or implicitly call the superclass constructor.

Avoid creating unnecessary objects
For non-mutable classes, you can typically use a static factory method instead of a constructor. The constructor creates a new object each time, and the static factory method does not.

When you turn a local variable into a final static domain, you can improve efficiency, but if you are not a common method, you can defer initialization, but make the implementation more complex.

adapters, views
An adapter is an object that delegates functionality to a fallback object, providing an alternative interface to the fallback object.
Long and long differences
Avoiding creating objects by maintaining your own pool of objects is not a good way to cook unless the objects in the pool are very heavyweight. A typical object instance that really uses the object pool correctly is the database connection pool. But it also increases the complexity of code and damages performance. The garbage collection period and the object pool performance of the JVM need to be weighed.
In a certain scenario, it is possible to create objects with repeatability to prevent security breaches and errors.

Elimination of expired object references
Cleans up expired references and can be empty. But generally not necessary, not elegant. In a memory-managed class, you need to clean up.

Weakhashmap is useful only if the lifetime of all cache entries is determined by the external reference of the key and not by the value.


Common sources of memory leaks:
Class manages its own memory;
Cache
Listeners and other callbacks.
Memory leaks are generally found through heap profier.

Avoid using the finalization method
The finalization method is often unpredictable and dangerous, and is generally unnecessary.
Time-focused tasks should not be done by the finalization method. Using the finalization method to close a file that is already open is a serious error because the descriptor of the open file is a very limited resource. Because the JVM delays the execution of the finalization method, a large number of files remain open and may fail to run when a program cannot open the file again.

Executing the finalization method in a timely manner is one of the main functions of the garbage collection algorithm, and this algorithm will be similar in different JVM implementations.
The Java language specification does not guarantee that the finalization methods will be executed in a timely manner, and that they are not guaranteed to be executed at all. When a program terminates, the finalization method on some objects that have not been accessed is not executed at all, which is entirely possible. The conclusion is that the method should not be finalized to update important persistent states.

The finalization method is caused by a very serious loss of performance.
Finalizer
A local peer is a local object, and a normal object is delegated to a local object by a local method.

End of chapter II

Effective Java Chapter II create and Destroy objects reading notes

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.