Ali Java development manual thinking summary

The difference between a good engineer and an average engineer is not that there are architectural diagrams flying around, but that his skills are reflected in every line of code he writes. – BiXuan

1. Naming style

Use UpperCamelCase for class names such as DO/BO/VO/PO

【 Abstract 】 The method uses lowerCamelCase style, try to be a verb

Small thought: for example, common

  • Get a single object, getUserById
  • Get the object no, listUserByGroupId
  • Count the number of objects countUserByClassId
  • Add,delete, insert,delete,update, etc

2. Constant definition

If the value of a variable changes only in a range, the type enum is used

Think about it: for example, order status in e-commerce can be listed with your finger. OrderSatausEnum = OrderSatausEnum = OrderSatausEnum

public enum OrderSatausEnum {
    TO_PAY(1."Payment on behalf"), PAID(2."Paid") ...;
    
    private Integer orderStatus;
    private String orderSatausDes;
    
    OrderSatausEnum(Integer orderStatus,String orderSatausDes) {
        this.orderStatus = orderStatus;
        this.orderSatausDes = orderSatausDes;
    }
    
    // get set
}
Copy the code

Furthermore, what if the order needs to be added to the “group waiting” status one day? So these configuration things, you can go to the configuration center. For example, Ctrip out of Apollo

3. The rules of OOP

Object’s equals method is prone to nulling pointer exceptions. Call equals using constants or identifying high-quality objects.

For example, TO_PAY equals(order.getorderstatus ()) The reverse is not true because order.getorderStatus () may be null.

Naturally, the java.util.Objects#equals utility class is more recommended.

The equals method is used to compare the values of all wrapper objects of the same type.

Little thought: Forget the ==. There are also a few things to note about equals, such as the status object of Byte type.

getStatus().equals(0) // Counterexample, false
getStatus().equals((byte)0) // true
Copy the code

If an Integer ranges from -128 to 127, it is normal. The reason is that objects in the range -128 to 127 are generated in integerCache. cache, which reuse objects. So, remember, don’t use ==, use equals.

4. Collection processing

Do not remove/add elements in a for loop. Remove Use the Iterator method. If concurrent operations are performed, lock the Iterator object.

How Iterator operates on sets can be done in baidu. This is a typical iterator design pattern, you can look at the source code of the others simple implementation principle, and can learn a high-level knowledge.

5. Concurrent processing

First, threads must be provided through a thread pool. Explicit creation of threads is not allowed. * Thread pools cannot be created by Executors. Use ThreadPoolExecutor instead. The following types of Threadpools created by Executors have their drawbacks:

  • FixedThreadPool and SingleThreadPool allow request queue length integer. MAX_VALUE, a large number of requests, resulting in OOM
  • The CachedThreadPool and ScheduledThreadPool allow the maximum number of threads to be created at Integer.MAX_VALUE

So, the reason to use ThreadPoolExecutor is to better understand how thread pools operate, avoid resource exhaustion, and better fit a business scenario to create a more appropriate thread pool.


In high concurrency scenarios, synchronization calls should consider the performance loss of locks. If you can use lock-free data structures, don’t use locks; If you can lock blocks, don’t lock the whole method body. If you can use object locks, don’t use class locks. That is, the smaller the granularity of locking, the smaller the performance loss. And the block of code that avoids locking calls RPC methods.

In addition, when multiple resources are locked at the same time, the lock sequence must be consistent. Otherwise, the lock sequence of one thread is ABC and that of the other is ACB or BAC, resulting in a deadlock. As shown in figure:


【 Abstract 】 Financial capital related information, use pessimistic lock. For example, update a user’s wallet balance field.

A quick thought: when I used to do P2P, I used MySQL row locks very simply.

SELECT * FROM xx WHREER xx.id=888 FOR UPDATE
Copy the code

Specific line lock, table lock we can baidu to understand.

6. Control statements

【 Abstract 】 High concurrency scenarios, such as the second kill scenario, commodity deduction inventory, inventory judgment do not use “equal” to judge the commodity inventory has been sold out conditions. Use greater than or less than conditions instead.

Ponder: This is a classic oversold scenario. Some people will ask that there will also be a few oversold problems? The answer is yes. But if you use equal, the number of oversold units is much, much higher, say 10,000 units. But overselling by 10,000 is not the same level of failure as overselling by 1. Or the difference between a malfunction and a non-malfunction.

7. Exception handling

【 Abstract 】 Abnormal should not be used to do process control, condition control

Small thought: yesterday, jingdong asked me, can this be downgraded? The following code:

try {
    searchFromES()
}catch(){
    searchFromDB()
}
Copy the code

That’s not a downgrade. That’s not how it works. First, the code is not written correctly, exceptions should not be used for process control, condition control. Second, this as long as the implementation of ES read problems, not read DB. Can consider the responsibility chain design pattern to achieve. The pseudocode is as follows:


ESHandle {
    void handle(a) {
        try {
            searchFromES()
        }catch(){
        }
    }
}

DBHandle {
    void handle(a) {
        try {
            searchFromES()
        }catch() {}}}// The two handles can be implemented using the responsibility chain.
Copy the code

8. Build table specifications and SQL statements

【 Abstract 】 When the number of rows in a single table exceeds 5 million or the capacity of a single table exceeds 2 GB, it is recommended to carry out database and table division.

If you don’t expect to reach this level of magnitude three years from now, do not create a separate table from the database.


Do not use count(column name) or count(constant) instead of count(*). Because it is a pre-shipment of standard statistical rows defined in SQL92. It counts rows that are NULL.


【 Abstract 】 Under the condition of where, the in can be avoided, we should pay attention to the number of sets in, control within 1000.


If count is 0, return empty list directly. Avoid the following paging statements.

9. The server

【 Abstract 】 It is recommended to reduce the TCP time_wait timeout for high-concurrency servers. /etc/sysctl.conf

net.ipv4.tcp_fin_timeout = 30
Copy the code

“Highlights” the JVM Settings – XX: + HeapDumpOnOutOfMemoryError. Make the JVM output dump information when it hits OOM.

Little Thought: This is important. Both must retain the incident server site. For example, OOM a server, in the VIP or what to pick the machine, so that the machine no longer have requests to enter. Then go to check dump information and check OOM problems.

Engineers for the code, must keep improving, whether from performance, or simple and elegant, have to keep improving the spirit of craftsmen, carefully polish their own work. – how long

This article is published by OpenWrite, a blogging tool platform