Alibaba Java development manual to learn the correct posture is what? Refresh your knowledge of the norms of the code

Many people know, Ali Baba in 2017 released "Ali Baba Java Development Manual", before and after the introduction of a number of versions, and introduced a complete set of plug-ins and IDEA in subsequent books.

In the beginning of the birth of this manual, it is inside Ali, when it caused widespread discussion. The final share of the manual to see the outside world, is the result of countless Ali Engineer "critical", can be said that the combination of the successful experience of numerous engineers, stepped on the pit.

In fact, the Statute of the greatest value, should encourage people to think about the thinking behind the development of the statute. Really to probe the rationale behind the statute, this process can learn a lot of things.

"Ali Baba Java Development Manual" can not be a small partner private letter I [Ali] receive a manual to learn

First, why Alibaba ban engineers directly using the log system (Log4j, Logback) in the API

Alibaba Java development manual to learn the correct posture is what?  Refresh code standards cognitive

 

In the Java eco-system around the logs, there are many proven solutions. About log output, there are two types of tools.

One is logging framework, mainly used for the output log, such as the output to which file, how to log format. Another one is the facade of the log, a primary common the API, is used to mask the differences between the various log frame.

So, for Java engineers, log on using the tool, the best practice is to use in applications such as Log4j combination + SLF4J to log output.

The greatest benefit of doing so, is the development of the business layer to achieve and do not care about the details of the underlying logging framework, the encoding time frame does not need to consider the costs arising from the future replacement. This is the facade of the benefits mode.

Second, why Alibaba is recommended set of initialization, the specified collection capacity size?

Alibaba Java development manual to learn the correct posture is what?  Refresh code standards cognitive

 

There HashMap expansion mechanism is that when the conditions will achieve expansion for expansion. If we do not set the size of the initial capacity, with the increasing elements, HashMap occur repeatedly expansion, and the expansion mechanism determines the HashMap each expansion will need to rebuild the hash table, is very affecting performance.

By default, when we set the initial capacity of the HashMap, HashMap will actually use this value is greater than the first power of 2 as the initial capacity.

However, in order to avoid the expansion caused by consumption of maximum performance, we recommend that you can change the default capacity digital set expectedSize / 0.75F + 1.0F. In the daily development, you can use

Map<String,String>map=Maps.newHashMapWithExpectedSize(10);

To create a HashMap, the process of calculating the guava will help us complete.

However, the above operation is a memory-changing performance with the practice, the use of real time, taking into account the impact of memory.

Third, why Alibaba ban remove / add elemental in foreach loop in operation

Alibaba Java development manual to learn the correct posture is what?  Refresh code standards cognitive

 

We use the enhanced for loop, in fact, is syntactic sugar provided by Java, its implementation principle is to traverse the elements of the aid Iterator.

However, if during traversal, not through the Iterator, but add / delete the collection by the collection method of the class itself. So when a traversal in an Iterator, has been tested and found to modify the operation once the set is not by itself, it may be happening concurrently executed other threads will throw an exception this time, the user is prompted to occur concurrent modification, which is the so-called fail-fast mechanism.

Of course, there are many ways to solve these problems. For example, using an ordinary cycle, using an Iterator element removal, use of Stream filter, the use of fail-safe and the like.

Fourth, Alibaba Why ban the SimpleDateFormat defined as static type?

Alibaba Java development manual to learn the correct posture is what?  Refresh code standards cognitive

 

SimpleDateFormat conversion can be done between primary String and Date, time can also be converted into an output time zones. But in concurrent scenario SimpleDateFormat is not thread-safe, and developers need to ensure their own safety.

SimpleDateFormat format method in the implementation process, will use a member variable calendar to save time. In fact, this is the crux of the problem.

If a SimpleDateFormat using a static definition. Then this SimpleDateFormat is a shared variable, followed, SimpleDateFormat in the calendar can also be accessed by multiple threads to. There will be complicated by security issues.

V. Why Alibaba is not recommended for use in the loop "+" string splicing

Alibaba Java development manual to learn the correct posture is what?  Refresh code standards cognitive

 

Use the + string concatenation, in fact, just a syntactic sugar provided by Java, decompile, we can see that, in fact, string constants using the "+" in the splicing process, after the String turned into StringBuilder, using its append method treatment.

If a for loop, a "+" stitching string, then each time there will be a new re the StringBuilder, and then converted into the StringBuilder String, then append.

And frequent new objects want to spend a lot of time, of course, will not only time-consuming, frequently create an object, it will result in a waste of memory resources.

VI. Why Alibaba require the programmer to modify the value of careful serialVersionUID field

Alibaba Java development manual to learn the correct posture is what?  Refresh code standards cognitive

 

Serialization provides a program that lets you even in the case of JVM shutdown can also save objects down the program. As we usually used as U disk. Sequence into Java objects may be stored or transmitted in the form (e.g. binary stream), such as stored in a file. Thus, when the object is required again, the file is read out from the binary stream, then deserialize the object from the binary stream.

Virtual machines allow deserialization, depends not only on the class path and function codes match, a very important point is whether the two classes of serialized ID consistent sequence of this so-called ID, that is, we define in the code serialVersionUID .

During deserialization, JVM will came byte stream serialVersionUID serialVersionUID with the respective local entity class are compared, it is considered to be consistent if the same can be deserialized, otherwise there will be a serialized version inconsistent exception, that is InvalidCastException.

Seven Why Alibaba requires careful use of the ArrayList method subList

Alibaba Java development manual to learn the correct posture is what?  Refresh code standards cognitive

 

List subList is a method defined in the interface, this method is mainly used to return a set period, can be understood as a collection of some elements, taken in his return value is a List.

But subList return is not a new List, but a view. That is, SubList did not re-create a List, but direct reference to the original List (returns a view of the parent class), just specify what range of elements he wants to use it (from fromIndex (included), to toIndex (not included)).

So the first thing we can not convert subList method to get a collection directly into ArrayList. Just because SubList internal ArrayList class, and no inheritance relationship between them, it can not be cast directly.

In addition, view and modify the original List also need to pay attention to several points, particularly the interaction between them:

  • 1, the parent (sourceList) promoter (subList) List of non-structural modifications do (non-structural changes), will affect each other.

  • 2, sub-List to make structural changes, the operation will also be reflected in the parent List.

  • 3. List the parent to do structural changes, will throw an exception ConcurrentModificationException.

So, Alibaba Java Developer's Handbook have another one states:

Alibaba Java development manual to learn the correct posture is what?  Refresh code standards cognitive

 

Eight Why Alibaba advises developers to use caution inheritance?

Alibaba Java development manual to learn the correct posture is what?  Refresh code standards cognitive


As an object-oriented development language, the Java code reuse is one interesting feature. Reuse Java code inheritance, as well as a combination of three specific proxy forms.

Inheritance, you must specify which class inherit specific when writing the code, so the class hierarchy is determined at compile time. And to the inheritance from the base class can not be changed dynamically at runtime, thus reducing application flexibility.

Combination, when writing the code for programming interfaces may be employed. Therefore, the combination of relationship classes generally determined at runtime. In addition, there are certain differences are code-multiplexed manner:

  • Inheritance structure, the internal details of the parent class for the subclass is visible. So we can say generally inherited through code reuse is a white cassette code reuse. If the base class is changed, then the derived class implementation will also change. This leads to unpredictable behavior of the subclass.

  • New combination is generated, by performing more complex functions assembly (composition) of an existing object. Because between objects, their internal details are not visible, so we can say that through a combination of code reuse code reuse is black cartridge. Because the portfolio is generally defined a type, so I do not know at compile specific methods which achieve class will be called.

There, Java does not support multiple inheritance, and the combination is not limited. Like a person can only have one father, but he can have a lot of cars.

Nine, Alibaba Why prohibit developers to use as a variable name isSuccess

Alibaba Java development manual to learn the correct posture is what?  Refresh code standards cognitive

 

fastjson jackson and when the target sequence into json string, is reflected by traversing all the getter methods in the class, and to give getHollis isSuccess, and according to the rules of JavaBeans, he will think this is a success and two properties hollis value.

But Gson not do so, he is traversing through all the attributes reflected in the class, and its value to serialize json

We can see that because of the different sequences of tools, making use of the time sequence of policy is not the same, therefore, the results for the same sequence of objects of the same class may be different.

If for the same object, I use fastjson be serialized, then use Gson deserialization, and this happens to be the object of a property is isXXX named, it will cause problems.

As developers, we should think of ways to try to avoid such problems, the POJO for designers, just to do a simple thing can solve this problem, and that is the isSuccess changed to success.

X. Why not let Alibaba use the COUNT (column name) or COUNT (constant) to replace the COUNT (*) it

Alibaba Java development manual to learn the correct posture is what?  Refresh code standards cognitive

 

Because COUNT (*) is the syntax of the number of rows SQL92 standard statistical definition, so he had a lot of MySQL optimization, MyISAM will be directly to the number of rows in the table separately recorded for COUNT (*) queries, InnoDB will in sweep when selecting the smallest index table to reduce costs. Of course, the premise of these optimizations are not conditional and inquiry where the group.

In InnoDB COUNT (*) and COUNT (. 1) is not implemented on the difference, and the same efficiency, but COUNT (field) field requires determination of non-NULL, so the efficiency will be lower.

Because the number of rows COUNT (*) is the syntax of the number of rows SQL92 standard statistical definition, and high efficiency, so please use the COUNT (*) query tables!

Why did the Alibaba Executors are not allowed to create a thread pool?

Alibaba Java development manual to learn the correct posture is what?  Refresh code standards cognitive

 

Java, there are two main BlockingQueue achieve, namely ArrayBlockingQueue and LinkedBlockingQueue.

ArrayBlockingQueue array is implemented by a bounded blocking queue capacity must be provided.

LinkedBlockingQueue a linked list is implemented bounded blocking queue capacity can be set to select, if not set, the queue is a non-blocking boundary, the maximum length of Integer.MAX_VALUE.

The problem here lies in: not set, it will be a non-blocking queue boundary of a maximum length of Integer.MAX_VALUE. That is, if we do not set LinkedBlockingQueue capacity, then its default capacity will be Integer.MAX_VALUE.

And when you create LinkedBlockingQueue newFixedThreadPool, the capacity is not specified. At this point, LinkedBlockingQueue is a borderless queue, the queue for a borderless, it can be continuously added to the task queue, in which case it is possible because too many tasks and lead to memory overflow.

The above mentioned problems mainly in newFixedThreadPool and newSingleThreadExecutor two factory methods, not to say newCachedThreadPool and newScheduledThreadPool two methods to secure the maximum number of threads created by these two methods may be Integer.MAX_VALUE, created so much thread, inevitably it may lead to OOM.

to sum up

After the above, is that I had some time to learn some of the rules by "Manual", summed up some of their own content, this process myself learn a lot of things.

So to say, this is the study "Handbook" correct posture, so as to maximize growth!

This series continues to update, the latter will be gradually improved. Welcome attention and communication.

Published 46 original articles · won praise 65 · views 3731

Guess you like

Origin blog.csdn.net/GYHYCX/article/details/104020490