preface

Reference: Alibaba Java Development Manual V1.3.0

Summarize important development protocols that are useful for interviews

1. Programming protocol

(a) naming style

  • [Mandatory] POJO class Boolean variables, do not add is, otherwise part of the framework parsing will cause serialization errors.

Counterexample: The basic data type is Boolean isDeleted. Property, whose method is also isDeleted(), RPC

During the reverse lookup, the framework thought that the corresponding attribute name was deleted. As a result, the attribute could not be obtained and an exception was thrown.

  • If a module, interface, class, or method uses a design pattern, use the pattern when naming it.

public class OrderFactory;

public class LoginProxy;

public class ResourceObserver;

(2) Constant definition

  • Force Does not allow any mana value (i.e. undefined constant) to appear directly in code.

Example: String key = “Id#taobao_” + tradeId;

cache.put(key, value);

  • If the value of a variable changes only in a range and has attributes that extend beyond its name, it is defined as an enumerated class.

Public Enum {MONDAY(1), TUESDAY(2), WEDNESDAY(3), THURSDAY(4), FRIDAY(5), SATURDAY(6),

SUNDAY(7); }

(iii) Code format

(4)OOP protocol

  • Avoid using a class’s object reference to access static variables or methods of that class, which unnecessarily increases compiler resolution costs.

  • [Mandatory] It is not allowed to modify the method signature of the interface that is being called externally or the interface that the library depends on to avoid impact on the interface caller. Obsolete interfaces must be annotated with @deprecated and clearly state what the new interface or service is being adopted.

  • 【 Force 】 Compare the values of all wrapper objects of the same type using equals.

Note: For Integer var =? In the range from -128 to 127, the Integer object is generated in integercache. cache and will reuse existing objects. The Integer value in this range can be determined directly by using ==, but all data outside this range will be generated on the heap. It does not reuse existing objects, which is a big pit and is recommended to use equals.

  • [Mandatory] Do not modify the serialVersionUID field when serializing new attributes of the class to avoid anti-sequence failure; Change the serialVersionUID value if the upgrade is completely incompatible to avoid deserialization clutter.

Note: Note that inconsistent serialVersionUID throws a serialization runtime exception.

  • [Mandatory] Constructor does not include any business logic, if there is initialization logic, please put it in init method.

  • POJO classes must write toString methods. Use the IDE tool: Source > generate toString

If you inherit from another POJO class, note that super.toString is preceded.

Note: When a method executes an exception, you can directly call the toString() method of the POJO to print its attribute values for easy sorting

Check problem.

  • [Recommendation] String concatenation in the loop body, which is extended by using the Append method of StringBuilder.

Note: Decomcompiled bytecode files show that each loop will new a StringBuilder object and proceed

The append operation returns a String object using the toString method, wasting memory resources.

Example:

String str = "start";
for (int i = 0; i < 100; i++) {
str = str + "hello";
}
Copy the code

(5) Collection processing

  • [Mandatory] Handle hashCode and equals according to the following rules:
    • 1) Whenever you override equals, you must override hashCode.
    • 2) Since Set stores non-repeating objects according to hashCode and equals, Set objects must override these two methods.
    • 3) If a custom object is used as a Map key, then hashCode and equals must be overridden.

Note: String overrides the hashCode and equals methods, so we can happily use String objects

Used as a key.

  • [Mandatory] The subList result of ArrayList cannot be forcibly converted to ArrayList, otherwise a ClassCastException will be thrown

Exception, that is, Java. Util. RandomAccessSubList always be cast to Java. Util. The ArrayList.

SubList returns the inner class subList of ArrayList, not ArrayList

A view of an ArrayList in which all operations on SubList sublists are eventually reflected on the original list.

  • ToArray (T[] array); list.size(); list.size();

Counter example: There is a problem with using the toArray method without arguments directly. This method can only return the Object[] class

A ClassCastException error occurs for a type array.

  • “Forced” to use tools Arrays. AsList () converts an array into a collection, you can’t use the modify the related methods of collection, it’s the add/remove/clear method will throw an UnsupportedOperationException anomalies.

The return object of asList is an inner array class that doesn’t implement collection modification methods. Arrays.asList

Represents the adapter mode, only the conversion interface, the background data is still an array. String[] str = new String[] { “you”, “wu” }; List list = Arrays.asList(str);

List. Add (“yangguanbao”); Runtime exception.

STR [0] = “gujin”; So list.get(0) will change as well.

  • Do not remove/add elements in a foreach loop. The remove element must be Iterator. If the operation is performed concurrently, the Iterator must be locked.

  • [Recommended] Pay close attention to whether the Map class K/V can store null values as shown in the following table:

(6) Concurrent processing

  • [Mandatory] Thread resources must be provided through a thread pool. Explicit creation of threads in an application is not allowed.

Note: The benefit of using a thread pool is to reduce the time spent creating and destroying threads, as well as the overhead of system resources and resolution costs

The problem of insufficient sources. If you don’t use thread pools, you can run out of memory or “overswitch” by creating a large number of similar threads.

  • 【 Mandatory 】 Thread pools cannot be created by Executors. Use ThreadPoolExecutor to clear the running rules of the thread pool and avoid resource depletion.

  • [Recommendation] Avoid Random instances being used by multiple threads. Although sharing the Random instance is thread-safe, it will degrade performance due to competing for the same seed.

Description: Random instances include instances of java.util.random or math.random ().

Example: After JDK7, API ThreadLocalRandom can be used directly, whereas before JDK7, encoding protection is required

Verify that each thread holds one instance.

  • Volatile Solves the problem of multithreaded memory not being visible. Multiple reads on one write can solve variable synchronization problems, but multiple writes cannot solve thread safety problems. For count++, use the following class :AtomicInteger count = new AtomicInteger(); count.addAndGet(1); If it is JDK8, the LongAdder object is recommended for better performance than AtomicLong (reducing the number of optimistic lock retries).

(7) Control statements

  • Avoid using if-else when expressing abnormal branches

Note: If you must use if()… else if()… else… Express logic in a manner that [forces] avoids subsequent code dimensions

Difficult protection, do not exceed 3 layers. Example: If-else code with more than 3 layers of logic can be implemented using guard statements, policy mode, state mode, etc.

Public void today() {if (isBusy()) {system.out.println (" change time. "); return; } if (isFree()) {system.out.println (" go to travel. "); return; } system.out. println(" Stay at home to learn Alibaba Java Coding Guidelines. "); return; }Copy the code

(8) Annotated regulations

(9) Others

  • [Mandatory] When using regular expressions, make good use of the pre-compilation function to effectively speed up the regular expression matching.

  • [Mandatory] Background variables sent to the page must be added $! {var} — exclamation point in the middle.

Note: If var=null or does not exist, ${var} is displayed directly on the page.

  • Math.random() this method returns a double. Note that the range 0≤x<1 (yes)

If you want to obtain a Random number of integer type, do not enlarge x by several times 10 and then round it, directly use the nextInt or nextLong method of Random object.

2. Exception log

(1) Exception handling

  • A class of RuntimeExceptions defined in the Java class library can be circumvented by pre-checking, but should not

Through the catch to handle, such as: IndexOutOfBoundsException, NullPointerException, etc. 阿鲁纳恰尔邦

If (obj! = null) {… }

Try {obj.method()} catch (NullPointerException e) {… }

  • [Mandatory] Exceptions should not be used for process control or condition control, because the processing efficiency of exceptions is lower than that of condition branches.

  • It is irresponsible to try and catch large chunks of code

  • [Force] Catch an exception to handle it, do not catch it and throw it away without handling anything. If you do not want to handle it, please

Throws the exception to its caller. The outermost business consumer must handle the exception and turn it into something that the user can understand.

  • 【 recommendation 】 Preventing NPE is the basic culture of programmers.

  • Whether to use “throw exception” or “return error code” in code is a must for external HTTP/API open interfaces

Use error code; In-app recommendation exceptions are thrown; The Result method is preferred for inter-application RPC calls, and the isSuccess() method, “error code”, and “error short message” are encapsulated.

(2) log protocol

  • [Mandatory] It is recommended that log files be saved for at least 15 days, because some exceptions occur in “weekly” intervals.

  • [Mandatory] Applications must rely on the API of SLF4J rather than the API of logging system (Log4j and Logback). Using the facade logging framework helps maintain and unify the log processing modes of each class.

Unit testing

  • Good unit tests must follow the AIR principles.

Note: When running unit tests online, it feels like AIR, but it is critical to ensure test quality. Good unit tests are, at a macro level, automated, independent, and repeatable. -a: Automatic -i: Independent -R: Repeatable

Iv. Safety Regulations

  • [Mandatory] Permission control verification must be performed on pages or functions belonging to users.

  • [Mandatory] The SQL parameters entered by the user are strictly bound with parameter or METADATA field values to prevent SQL injection.

Disallow string concatenation SQL from accessing the database.

  • [Mandatory] Any parameter passed in the user request must be validated.

MySQL database

(1) Table construction protocol

  • [Mandatory] Char is used as a fixed-length string if the stored strings are nearly equal in length.

  • [mandatory] A yes or no field must be named is _ XXX and the data type is unsigned tinyint (1 for yes, 0 for no).

    • Note: Any field that is non-negative must be unsigned.
    • For example, the field name for logical deletion is is_deleted. 1 indicates that the field is deleted, and 0 indicates that the field is not deleted.
  • [Mandatory] VARCHar is a string of variable length. Storage space is not allocated. The length cannot exceed 5000

If the value is greater than this value, define the field type as text, create an independent table, and use the primary key to correspond to it, so as to avoid affecting the efficiency of other fields.

  • [Mandatory] Three columns are required in the table: ID, GM_ CREATE, GM_ modified.
    • Note: ID must be the primary key, the type is unsigned Bigint, and the step size is 1. gmt_create,

Gmt_modified is of date_time type, with the former present tense indicating active creation and the latter past participle indicating active update.

  • [Recommendation] Fields allow some redundancy to improve query performance, but data consistency must be considered. Redundant fields should follow:
    • 1) Fields that are not frequently modified.
    • 2) VARCHAR is not a long field, let alone a text field.
    • Example: The name of commodity category is used frequently and the field length is short. The name is basically unchanged and can be stored redundantly in the associated table

Store category names to avoid associated query.

(2) Index protocol

  • [Mandatory] A unique index must be created for a field that has a unique feature, even if it is a combination of multiple fields.

  • [Mandatory] Disallow join when more than three tables are used. The data types of the fields to be joined must be absolutely consistent. In the case of multi-table associated query,

Ensure that the associated field has an index.

  • [Mandatory] When creating an index on a VARCHAR field, the index length must be specified

The actual text distinction determines the index length.

  • [Mandatory] Page search is strictly prohibited from left blur or full blur, if necessary, please go to the search engine to solve.

  • [Recommendation] Use overwrite indexes to perform query operations to avoid returning to the table. Explanation: If a book needs to know the title of chapter 11, will it turn to the page corresponding to chapter 11? Directory browsing

That’s it. This directory serves as an overwrite index.

Example: Types of indexes that can be created: primary key index, unique index, normal index, and overwrite index is one type of query

Effect, with the explain result, the extra column will appear: using index.

  • When creating a composite index, the most distinguishable index is at the far left.

If a=? and b=? , the value of column A is almost unique, so only idX_A index is needed

Can be.

(3) SQL statement

  • [Mandatory] Do not replace count(*) with count(column name) or count(constant), count(*) is defined by SQL92

Standard row count syntax, database independent, NULL and non-NULL.

  • [Mandatory] Do not use foreign keys and cascading. All foreign key concepts must be resolved at the application layer.

    • Student id = foreign key; student id = foreign key; student id = foreign key; If the student ID in the student table is updated and the student ID in the score table is triggered, a cascading update is made. Foreign keys and cascading update are suitable for low-concurrency single machine, but not for distributed and high-concurrency cluster. Cascading update is strongly blocked, and there is the risk of database update storm. Foreign keys affect database insert speed.
  • [Mandatory] Do not use stored procedures. Stored procedures are difficult to debug, expand, and transplant.

(4)ORM mapping

  • [Mandatory] In table query, do not use * as the query field list, which fields must be clearly stated.

6. Engineering structure

(a) application of stratification

(2) Two-party library dependence

(3) server

  • [Recommendation] You are advised to reduce the TIME_ wait timeout of TCP for high-concurrency servers.
    • Note: By default, the operating system closes a connection in time_ WAIT state after 240 seconds. In the case of high concurrent access, the server may be unable to establish new connections due to the large number of connections in time_ wait state. Therefore, you need to adjust the waiting value of this parameter on the server.
    • Example: On a Linux server, modify the /etc/sysctl. conf file to change the default value (seconds).

net . ipv 4. tcp _ fin _ timeout = 30

  • [Recommendation] Increase the maximum number of File handles (fd) supported by the server.
    • Note: Mainstream operating systems are designed to manage TCP/UDP connections in the same way as files, that is, a connection pair

Should be in a FD. The default maximum number of FDS supported by mainstream Linux servers is 1024. When the number of concurrent connections is large, it is easy to cause an “Open Too many Files” error due to insufficient FDS, resulting in the failure to establish new connections. It is recommended to increase the maximum number of handles supported by a Linux server several times (depending on the amount of memory on the server).

  • To recommend 】 【 JVM Settings – XX: + HeapDumpOnOutOfMemoryError parameters, letting the JVM when encountering the OOM scene output

Dump information.

  • In an online production environment, JVM Xms and Xmx are set to the same size of memory capacity, avoiding heap adjustment after GC

The pressure of size.

  • Internal server redirection uses forward; External redirect addresses are generated using the URL assembly utility class, otherwise

Inconsistent URL maintenance and potential security risks may occur.

Pay attention to my

I am man three dao dao, currently for the background development engineer. Focus on backend development, network security, Python crawler and other technologies.

Come and chat with me on wechat: yangzd1102

Github:github.com/qqxx6661

Original blog main content

  • Written interview review knowledge handbook
  • Leetcode algorithm
  • Sword point offer algorithm analysis
  • Python crawler related technical analysis and practice
  • Background development related technical analysis and actual combat

Personal public account: Rude3Knife

If this article is helpful to you, save it and send it to your friends