Alibaba Java Work Manual---learning notes __java

Source: Internet
Author: User
Tags volatile

This article is from: Head of Java

Recently browsed Alibaba's Java development manual, the feeling content is really very good, found a lot of their own in the programming of the misunderstanding, so decided through a written firm grasp, the text will select the more important part of the description and analysis. "Willing to stand on the shoulders of giants, code out efficient, code out of quality." Overview

There are a lot of contents in the handbook, including coding protocol, engineering structure, MySQL database, Exception Log, security protocol, Unit test, etc. 6. The engineering structure part in the overall project carries on the control, the coding stipulation and the MySQL design statute has very many "best practices", the individual thinks is the most valuable part. The Sub-key security protocol meets the needs of the internet scene, and the Exception Log and unit Test section are relatively small in content and value.
The following figure is a simple summary of a person's manual (drag the picture to the browser's new page, after which the magnification can be much clearer), where the Red Star is the focus, yellow for the secondary point. In addition, the collection processing, concurrent processing, MySQL protocol and engineering structure have a certain degree of difficulty, will be specifically put to the focus of the section to enhance the detailed analysis. Of course, this is a personal humble opinion, the full part of the bottom of the reference materials, the current Ali company has introduced this set of specifications of the IDE plug-ins, we can try. Strengthening engineering structure with heavy and difficult points

Open Interface: Provides RPC or restful-style interface, and through the framework of Gateway security control, flow control, and so on.
 Terminal display layer: The front-end template renders and executes the displayed layer.
Web Layer: Mainly to the access control forwarding, all kinds of basic parameters check, or no longer use the business simple processing.
Service Layer: Business logic services layer.


Manager Layer: This is a more interesting layer that includes both the common external interface's agent capabilities, the simple encapsulation of the DAO interface for reuse, and the ability to build a cache of DAO.
DAO Layer: Data interaction with the underlying MySQL, HBase, and so on, usually based on various DAL frameworks.
Externalinterface: Includes other departments RPC open Interface, base platform, other company's HTTP interface.
Tip: In the actual project, you can follow the pattern to build the package hierarchy. Collection Processing

Set operations have always been a key point, common tricks include the unique characteristics of the set element, you can quickly on a set to be JD8, in the steam stream to the collection operation did a good increase. Reasonable use of the ordered (sort) and stability (order) of the set to avoid the disorder of the set (Unsort) and
The negative effect of instability (Unorder) is that ArrayList is Order&unsort;hashmap Unorder&unsort;treeset is order&sort.


TIp: Different types of map collection k/v can not store null values as shown in the following table concurrency processing

Reasonable use of concurrency control to efficiently utilize system resources is an engineer's eternal pursuit, the manual of many requirements of a good understanding of their shortcomings in this area.


Creation of thread pools
The past half of the executors to create a thread pool, in fact, this is unreasonable, such as Fixedthreadpool blocking queue size integer.max_value, it is easy to cause a large number of requests piled up, causing oom. And Scheduledthreadpool allow the number of threads to be integer.max_value, more likely to appear oom. Therefore, you must use Threadpoolexecutor to create a thread pool, and explicitly set parameters for the thread pool.


The principle of using locks
1. When concurrency is high, synchronous calls should consider the performance loss of the lock. Can use unlocked data structure, do not use lock, can lock block, do not lock the whole method body, can use object lock, do not use class lock.
2. When you lock multiple resources, database tables, and objects simultaneously, you need to maintain a consistent lock order, or you may cause deadlocks.
3. When you modify the same record concurrently, avoid the loss of updates and require a lock. Either lock in the application layer or lock the cache, or use optimistic locks at the database level, using version as the update basis. If the probability of each access violation is less than 20%, optimistic locks are recommended, otherwise pessimistic locks are used. The number of retries for an optimistic lock must not be less than 3 times.


Countdownlatch
With Countdownlatch asynchronous synchronous operations, each thread must call the countdown method before exiting, and the thread executes the code to notice the catch exception, ensuring that the countdown method is executed to avoid the main thread from executing to the await method until the timeout is returned. Note that the child thread throws an exception stack that cannot be caught in the try-catch block of the main thread.


Threadlocalrandom
Avoid Random instances being used by multithreading, although it is thread-safe to share the instance, but performance degradation due to competition for the same seed is recommended for use with Threadlocalrandom.


Volatile
Volatile solves the problem of not-visible multithreading memory. For more than one read, you can solve the problem of variable synchronization, but if you write more, you will not be able to resolve thread safety issues. You can use the volatile keyword to implement deferred initialization when you complete a single case pattern for full Han.


Longadder
For count++ operations, you can use atomicinteger count = new Atomicinteger (), and Longadder is recommended in JDK8 to improve performance by reducing the number of retries for optimistic locks.


HashMap
HashMap can avoid this risk by using other data structures or locks during the development process because of high concurrency, which may lead to a dead chain when there is not enough capacity to resize the CPU.


ThreadLocal
The ThreadLocal object recommends the use of static adornments. This variable is shared for all operations within a thread. MySQL Protocol

Database optimization has been bothering me, the book on a few principles to give individuals in the database optimization of a lot of inspiration.


Index length
In the past has not been aware of the concept of the index also has a length, it is now known that in the VarChar Type field index, you can specify the index length, to a certain degree of differentiation, generally for string type data, length of 20 index, the degree of discrimination will be up to 90%, you can use count Distinct left (column name, index length))/count (*) to determine the degree of discrimination.

In addition, the page search is strictly prohibited left blur or full blur, if necessary, please go to the search engine to solve. The index file has the leftmost prefix matching attribute of B-tree and cannot be used if the left value is not determined.


ORDER BY
In the scenario with order by, be aware of the ordering of the index. For example where a =? and B =? The index of order by C is a _ b _ C


Overwrite Index
By using the overlay index, you can reduce the original table query and find the required information through the index page (TOC). Generally, the types of indexes that can be indexed include primary key index, unique index, normal index, and overlay index is an effect of the query, you can see through the Explain extra column will appear using index.

Page-Search
MySQL does not skip the offset line, but take the offset + N line, then discard the offset row, return the desired N rows, when the data volume is high, recommend the following way to optimize. Quickly locate the ID segment that you want to get, and then associate:
Select a.* from Table 1 A, (select ID from table 1 where condition LIMIT 100000,20) b where a.id=b.id SQL performance optimization targets
At least the range level is required, which is the ref level, if it can be consts best.


Consts only one matching row (primary key or unique index) in a single table can be read in the optimization phase.
Ref refers to the use of a normal index (normal).
Range retrieves the index.
Tip:type = index, indexed physical files full scan, very slow, this index level comparison range is also low, and full table scan is dwarfed.

The workbench in MySQL is slightly different: consts does not change, Non-unique Key lookup represents ref, Index range Scan represents range, full table scan represents all, and full Index s Can represents index, and of course you can choose Tabular view instead of visual view.

Composite Index
The highest degree of discrimination is at the leftmost, for where a =? and B =?, the more the value of column A is, the better. In addition, when an index is in progress, the column of the equal sign condition is placed in front of it when there is a mixed judgment condition for the inequality and equals sign.
Implicit conversions
Prevents implicit conversions due to different field types, resulting in index invalidation, which also needs to be considered as an important consideration when data query times out.

Resources

Alibaba Java Development Manual

Ali statute GitHub

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.