Effective Java reading notes

Source: Internet
Author: User

2015 progress is very small, read the book is not many, feel that they are going to waste, 2016 is a year of precipitation, in this year to continue to learn, read, and strive to improve their

In 16, 12 books were to be read, mainly related to Java Foundation, Spring Research, Java concurrency, JVM, and distributed. In this year's interview is a hit, everywhere is the distributed, clustered? Is it so cool to work for two or three years now? All in the distribution, the cluster and the like?

The 2016 book list is as follows:

1. In-depth understanding of Java Virtual machines: JVM advanced features and best practices---(see, expected three times this year)

2. Oracle query optimization rewriting techniques and case---(viewed)

3. Effective Java---(viewed)

4, spring3.x Enterprise application development actual combat

5, Spring Technology Insider: In-depth analysis of spring architecture and design principles---(This book has been read over last year, this year in a good study)

6. The art of Java concurrent programming

7, Java Concurrent Programming Combat---(this book has been read over the last year, this year in a good study)

8. Web-based system and Java middleware Practice

9. Principle and practice of distributed service framework

10, large-scale distributed Web site architecture design and practice

11, from Paxos to zookeeper distributed consistency principle and practice

12. High-performance MySQL

Three books have been read: In-depth understanding of Java Virtual machines: JVM advanced features and best practices, Oracle query optimization rewriting techniques and cases, effective java. Which in-depth understanding of the JVM this book is really a book of God, after reading really a kind of enlightened feeling, look forward to three times after giving me clairvoyant feeling. Oracle query optimization, feel like a general. Effective Java, the four conquered interpretations of the Bible.

Gentlemen, what a good book, trouble recommended, LZ greatly appreciated!

LZ did not read a book, will make some notes, of course, these are just notes! Just started a bit humble, don't mind, if you still a little help, LZ a contented!

Ii.: Creating and destroying objects

2.1. Consider replacing the constructor with a static factory method

1.2. Hardening the Singleton property with a private constructor or enumeration type

1.4. The ability to harden non-instancing through a private constructor.

1.5. Avoid creating unnecessary objects.

Take precedence over the basic type rather than the boxed base type, and beware of the involuntary automatic boxing.

1.6. Elimination of expired object references

If a stack grows first and then shrinks, then the objects that are popped from the stack will not be garbage collected, even if the program using the stack no longer references those objects, they will not be recycled. This is because the stack internally maintains this out-of-date reference to these objects. The so-called expired reference refers to a reference that will never be lifted again.

In general, we are emptying these references for outdated references (that is, set null), but this is bound to cause the program to become very confusing, and the best way is to let the variable containing the reference end the life cycle.

Common sources of Memory overflow are: 1, expired references, 2, caches, 3, listeners, and other callbacks. For the cache our usual practice is to periodically clear some unused items, think of the cache has been stored for several years of useless items are not all feel nauseous? The callback is to save only their weak references, such as the key that only saves them as Weakhashmap.

Memory leaks can be analyzed with the heap Profiler tool

Iv. Classes and Interfaces

4.1. Minimizing the accessibility rows of classes and members

Good module design can hide all the implementation details, his API and specific implementation clearly isolated, modules and modules only through their API communication, one module does not need to know the internal work of other modules---information hiding.

4.2, to minimize the variability of

1) to make the class immutable, you need to follow these rules:

1. Do not provide any method that modifies the state of the object

2. Ensure that classes are not extended

3. All domains are final and private

4. Ensure mutually exclusive access to any mutable component.

2) Benefits of immutable classes

1. Immutable object nature is thread-safe and does not require synchronization

2. Immutable objects provide a large number of artifacts for other objects

3) The disadvantage is that you need to provide different objects for each of the different values. If you create a larger object, the cost is a little higher.

In order to immutability, class is definitely not allowed quilt class, we first think of is "final" decoration, in fact, in addition to this there is a better way: all the constructors of the class all become private, and provide a public static factory.

4.3. Combination and inheritance

Take precedence over combinations and use inheritance with caution.

Please remember the following two words:

Inheritance should be used with caution, and its use is limited to situations in which you are certain that the technology is valid. One way to judge this is to ask yourself if you need to move up from a new class to a base class. If it is required, then inheritance is necessary. Conversely, you should consider whether you need to inherit. The idea of Java programming

Inheritance is only appropriate if the subclass is really a subclass of a superclass. In other words, for two classes A and B, only if there is a real

Is-a

Relationship, Class B should continue with Class A. "Effective Java"

4.4, interface, abstract class

1. Interface is the ideal choice for defining mixin

2. Interface allows us to construct a type framework for non-hierarchical interfaces

3. Skeleton Implementation Class

By providing an abstract skeleton implementation class for each of the important interfaces you export, combine the advantages of interfaces and abstract classes. At this point the function of the interface is still the definition type, but the skeleton implementation class takes over all the domain interface implementations related to the work. Skeleton implementations are called Abstractinterface.

The beauty of skeleton implementations is that they provide implementation assistance for abstract classes, but do not impose strict restrictions that are unique to "abstract classes are used as defined types." At the same time, when writing skeleton implementations, it is generally necessary to study the interface carefully and determine which methods are the most basic, and other methods can be implemented according to them. These basic methods will become abstract methods in the Skeleton implementation class (here is the template method pattern??). )。

4. Interfaces are used only to define types.

5. Constant interfaces are not worth emulating, interfaces should only be used to define types and should not be used to export constants.

6. For the use of constants we should follow the following rules: If the constants are closely related to an existing class or interface, these constants should be added to the class or interface, and if the constants are best considered to be members of the enumeration type, they should be exported with enum types Otherwise, you should use a non-instantiated tool class to export these constants.

4.5 Internal Classes

The primary role of the inner class should be to provide services only for his peripheral classes. There are four main types of internal classes: static member class, non-static member class, anonymous class, local class.

A static member class is commonly used as a public auxiliary class and only makes sense if it is used with its external classes. private static member Class A common method is to represent the component of the object that the perimeter class represents, and he does not need to rely on the perimeter class.

Anonymous inner class does not have a name, it is not a member of the perimeter class, it is not declared with other members, but is declared and instantiated at the same time as it is used. In the process of use, they cannot be instantiated except when they are declared. Anonymous classes have three common uses: Dynamically creating function objects, creating process objects (runable, Thread, Timetask), and interior of static factory methods.

Five, generic type

Generics are recommended, although they will be erased at run-time.

Eliminate every non-inspected warning, as much as possible. If you cannot dismiss the warning and you can prove that the code that caused the warning is type-safe, you can use the @suppresswarnings ("unchecked") annotation to suppress the warning, and we must use the annotation in a potentially small scope, prohibiting the use of the annotation on the entire class.

Vii. methods

7.1 When necessary, the constructors and access methods for immutable objects are checked for protection.

7.2, careful design method signature

1. Choose the name of the method carefully: The method name should always follow the standard naming conventions.

2. Do not go too far in the pursuit of a convenient approach, and each method should do its utmost to the best of its ability.

3. Avoid too long parameter lists, providing four parameters or less on one side.

There are three ways to avoid too long a parameter: 1). Break the method into multiple Method 2). Create auxiliary classes to protect the grouping of parameters 3). Calls from object build to method are in builder mode.

4. Use interfaces rather than implementation classes as parameter types. You should not take HashMap as a parameter!!

7.3, cautious use of heavy

1. Method overloads are determined at compile time.

2. Never export two overloaded methods with the same number of parameters, which is a safe and conservative approach.

3. Any given set of actual parameters will be applied to that overloaded method.

4. The same set of parameters can be passed to different overloaded methods only through type conversion, and if this is not avoided, it should be ensured that the behavior of all overloaded methods must be consistent when passing the same arguments.

7.4. Use variable parameters with caution

A mutable parameter accepts 0 or more parameters of a specified type. The mechanism is to first create an array whose size is the number of arguments passed at the call location, pass the parameter values to the array, and finally pass the array to the method.

7.5. Returns an array or set of 0 lengths, rather than null. Not important but worth noting.

Viii. General Programming

8.1 Minimization of local variable scopes

Minimizing the scope of local variables can enhance the readability and maintainability of your code and reduce the likelihood of errors.

If the scope of a local variable is minimized, the most powerful way is to declare it where it was first used. In general, each local variable should have an initialization, and if there is not enough information to initialize the variable meaningfully, the declaration of the variable needs to be deferred until it can be initialized.

For methods, the method should be as small and centralized as possible so that the scope of the local variable can be minimized as much as possible.

8.2, priority to use For-each cycle

The For loop can make local variables smaller compared to the while loop, while the program is shorter and enhances readability.

The For-each cycle has the advantage of a traditional for-loop unmatched in simplicity and bug prevention, and there is no performance penalty, so we should use the For-each loop as much as possible, but whether the For-each loop is not available in the following three scenarios:

1. Filtering: If you need to traverse a collection and delete a specific element, you need to use the displayed iterator.

2. Conversion: If you need to traverse a list or an array and replace some or all of its element values, then an iterator is required to set the value of the element.

3. Parallel iterations

8.3. Priority use of basic types

The basic type is equivalent to a reference type with the following differences: 1.) The base type has only values, and the reference type has a different identity than their value, and it says new Integer (1)! = new Integer (1), 2). The base type has a fully functional value, and the reference has a null value of 3 ). Basic types are generally more space-and time-saving than reference types.

When you mix a base type with its reference type in an operation, its reference type automatically does the unboxing action.

There is a need to pay extra attention to the unboxing mechanism when iterating, as frequent unboxing of crates can lead to degraded performance.

Other

1. If you need an accurate answer, use bigdecimal instead of double and float.

2. If a suitable interface type exists, then for parameters, return values, variables, and domains, the interface type should be used for declaration.

Nine, abnormal

Exceptions should only be used in the case of exceptions, they should never be used for normal control flow.

The exception mechanism is designed to be used in unusual situations, so very few JVMs are optimized by the JVM, so the exception generally runs slower.

We should try to make the exception code block small because try: Catch prevents the JVM from implementing some specific optimizations that might otherwise have to be performed.

Author: If you think the article is helpful to you, do not forget to recommend or share, because your support, is I continue to write the power and source of the next chapter!


3--------------------

Effective Java reading notes

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.