Valid Java Reading Notes

Source: Internet
Author: User

Valid Java Reading Notes
Introduction creating and destroying objects

When and how to create objects, when and how to avoid object creation, how to ensure that the created objects can be destroyed in a timely manner, and how to manage all the clear work that must be done before destruction

Article 21 The major difference between the static factory method and the constructor in consideration of replacing the constructor with the static factory method is that they have the following two advantages: instead of creating a new object each time you call them, the static factory method is different from the constructor. The third advantage is that they can return any child type objects of the original return type.

The service provider framework consists of three components:

Service InterfaceProvider implementation
Provider registration APIThe system is used to register the implementation and allow the client to access
Service access APIThe client obtains the service instance.
Service Provider Interface (optional)Creates instances for Service implementation.

Sample Code

public interface Service{    public void service();}public interface Provider{    Service newService();}public class Services{    private Services(){}    private static final Map< String, Provider > = new ConcurrentHashMap< String, Provider >();    public static final String DEFAULT_PROVIFER_NAME = "
  
   ";    public static void registerDefaultProvider( Provider p )    {        registerProvider( DEFAULT_PROVIDER_NAME, p );    }    public static void registerProvider( String name, Provider p )    {        providers.put( name, p );    }    public static Service newInstance()    {        return newInstance( DEFAULT_PROVIDER_NAME );    }    public static Service newInstance( String name )    {        Provider p = providers.get( name );        if ( p == null )        {            throw new IllegalArgumentException( "No provider registered with name : " + name );        }        return p.newServices();    }}
  
The fourth advantage of static factory methods is that they make code more concise when creating parameterized instances.
Simplify generic code through syntactic sugar
public static< K, V > HashMap< K, V > newInstance(){    return new HashMap< K, V >();}Map< String, List< String > > map = HashMap.newInstance();
The main disadvantage of the static factory method is that, if the class does not include public or protected constructors, the second disadvantage of the static factory method of the category cannot be quilt, they are no different from other static methods.
Common static factory method names:
ValueOfThe returned instance has the same value as its parameter, which is actually a type conversion method.
OfValueOf substitution
GetInstanceReturn the corresponding instance based on the method parameters. For Singleton, if there is no parameter, return a unique instance.
NewInstanceSimilar to the getInstance function, make sure that each of the returned instances is newly created.
GetTypeSimilar to the getInstance function, it is used when the factory method is in a different class. Type indicates the object Type returned by the factory method.
NewTypeSimilar to the newInstance function, it is used when the factory method is in a different class.
Article 21 When encountering multiple constructor parameters, consider the limitations of using the builder's static factory and constructor: ** it cannot be well extended to a large number of optional parameters **

The overload constructor mode is feasible, but when there are many parameters, the client code will be difficult to write and difficult to read.

** One solution **: In the JavaBean mode, call a non-argument constructor to create an object, and then call the setter method to set each required parameter, as well as potential problems with each related optional parameter: the status is inconsistent, which prevents the possibility of changing the class, and the security and readability compromise of the ** Builder mode **.

Instead of directly generating the desired object, the client calls the constructor using all necessary parameters to obtain a builder object, and then the client calls a method similar to setter on the builder object, and the client calls the build method without parameters to generate immutable objects.

Sample Code
public class NutritionFacts{    private final int seringSize;    private final int servings;    private final int calories;    public static class Builder    {        private final int servingSize;        private final int servings;        private final int calories = 0;        public Builder( int servingSize, int servings )        {            this.servingSize = servingSize;            this.servings = servings;        }        public Builder calories( int val )        {            calories = val;            return this;        }        public NutritionFacts build()        {            return new NutritionFacts( this );        }    }    private NutritionFacts( Builder builder )    {        servingSize = builder.servingSize;        servings = builder.servings;        calories = builder.calories;    }}//call codeNutritionFacts cocaCola = new NutritionFacts.Builder( 240, 8 ).calories( 100 ).build();
** Builder mode simulates named optional parameters ** in Java, the traditional abstract factory implementation is a Class object, and the newInstance method is used as part of the builer method. However, the newInstance method always tries to call the Class's no-argument constructor, but the constructor may not exist. At the same time, this method will also spread the exception thrown by the no-argument constructor, ** 'class. newInstance 'destroys the exception check during compilation ** builer is insufficient: to create an object, you must first create its builder, which may cause performance problems. This is more lengthy than the overlapping builder mode, it is used only when many parameters are used.

If the class constructor or static factory has multiple parameters, the Builder mode is a good choice during design.

Article 21 using a private constructor or enumeration type to enhance the Singleton attribute to make the class Singleton makes it very difficult for the client to test, because it cannot be replaced by its Simulated Implementation, unless a Singleton method that acts as a type interface is implemented
public class Elvis{    public static final Elvis INSTANCE = new Elvis();    private Elvis() { ... }    public void leaveTheBuilding() { ... }}//anotherpublic class Elvis{    private static final Elvis INSTANCE = new Elvis();    private Elvis() { ... }    public static Elvis getInstance() { return INSTANCE; }    public void leaveTheBuilding(){ ... }}

Privileged clients can useAccessibleObject.setAccessibleMethod To Call The private constructor through the reflection mechanism

The third method of Singleton is to compile an enumeration type that contains a single element.
public enum Elvis{    INSTANCE;    public void leaveTheBuilding() { ... }}
It is more concise and provides a serialization mechanism free of charge, which absolutely prevents repeated instantiation, ** the enumeration type of a single element has become the best way to implement Singleton ** 4th attempts to use the private constructor to enhance the non-instantiation ability to force the class to be instantiated by making the class an abstract class, is a private constructor implementation that does not work
public class UtilityClass{    private UtilityClass()    {        throw new AssertionError();    }}
5th avoid creating unnecessary objects. In general, it is better to reuse objects instead of creating a new object with the same function whenever necessary.
String s = new String( "stringtest" );//Donot do thisString s = "stringtest";
For immutable classes that provide both static factory methods and constructors, the static factory method is usually given priority to avoid creating unnecessary objects.
public class Person{    private final Date birthDate;    //Donot do this    public boolean isBabyBoomer()    {        Calendar gmtCal = Calendar.getInstance( TimeZone.getTimeZone("GMT") );        gmtCal.set( 1946, Calendar.JANUARY, 1, 0, 0, 0 );        Date boomStart = gmtCal.getTime();        gmtCal.set( 1965, Calendar.JANUARY, 1, 0, 0, 0 );        Date boomEnd = gmtCal.getTime();        return birthDate.compareTo( boomStart )>=0                && birthData.compareTo( boomEnd )<0;    }}//better implementspublic class Person{    private final Date birthDate;    private static final Date BOOM_START;    private static final Date BOOM_END;    static    {        Calendar gmtCal = Calendar.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();    }    //Do this    public boolean isBabyBoomer()    {        return birthDate.compareTo( BOOM_START)>=0                && birthData.compareTo( BOOM_END)<0;    }}
** Priority should be given to basic types instead of basic types. Be careful when automatically packing them ** it is not a good practice to avoid object creation by maintaining your own object pool, unless the objects in the pool are very heavyweight, the typical object example for correct use of the Object pool is the database connection pool. Generally, maintaining your own object pool will increase the complexity of the code and increase the memory usage, it also damages the performance.

Do not create new objects when reusing existing objects.
When creating a new object, do not reuse the existing object.
When we advocate the use of protective copies, the cost for reusing objects is much higher than the cost for Creating duplicate objects.
If a protective copy is not implemented if necessary, it will lead to potential errors and security vulnerabilities. Unnecessary object creation will only affect the style and performance of the program.

Article 21 remove expired object references. Expired references are never released. If an object reference is unconsciously retained, the garbage collection mechanism not only does not process this object, but also does not process all other objects referenced by this object.

Clearing object references is an exception, not a standard action
As long as the class manages its own memory, we should be cautious about memory leakage.

Another common source of Memory leakage is ** cache **: as long as there is a reference to the key of an item after the cache, this item makes sense and can be represented by 'weakhashmap; when an item in the cache expires, it is automatically deleted.

Only when the life cycle of the cache item is determined by the external reference of the key rather than the value,WeakHashMapIs useful

The third common source of Memory leakage is ** listeners and other callbacks **: the best way to ensure that Callbacks are immediately treated as garbage collection is to save only 7th weak references to them and avoid using the finalize method ** is usually unpredictable, it is also very dangerous. In general, it is not necessary to ** terminate the method. The disadvantage is that it cannot be guaranteed that the Java language specification will be executed in a timely manner. It is not guaranteed that the termination method will be executed in a timely manner, in addition, it is not guaranteed to be executed. ** you should not rely on the termination method to update important persistent states. ** there is a very serious performance loss when using the termination method. For methods that do need to be terminated, ** provide a display termination method **, it is also required that the client to change the class call this method when every instance is no longer useful ** the explicit termination method is usually used in combination with the try-finally structure, to ensure timely termination ** the termination method has two valid purposes: when the object owner forgets to call the explicit termination method, the termination method acts as a "security net" and is related to the local peer of the object. A local peer is a local object. A common object is delegated to a local object through a local method. The Garbage Collector cannot perceive the existence of a local object. When a Java peer is recycled, it will not be recycled.

The "End method chain" is not automatically executed and needs to be explicitly called.
Another optional method isEnd method defender

Common methods for all objects

In-depth analysis of equals, hashCode, toString, clone, and finalize

Class and Interface

Guiding principles for classes and interfaces

Generic enumeration and annotation Methods

How to process parameters and return values, how to design method signatures, how to write documents for methods, and further improve availability, robustness, and flexibility

General Program Design

Discusses the processing of local variables, control structures, usage of class libraries, usage of various data types, reflection mechanisms, and usage of local methods, and discusses optimization and naming conventions.

Exception

How to take advantage of exceptions, improve program readability, reliability, and maintainability, reduce the negative impact of improper use, and provide guidelines for abnormal use

Concurrent serialization

Describes the serialization technology and discusses the serialization proxy mode.

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.