Ali JAVA Statute - the thread pool is not allowed to create Executors

  1. Timely clean-up code segment is no longer used or configuration information. Note: For outdated garbage code or configuration, and resolutely clean up procedures to avoid over-bloated, code redundancy
    Positive example: For codes which are temporarily removed and likely to be reused, use /// to add a reasonable note.
     public static void hello() {
        /// Business is stopped temporarily by the owner.
        // Business business = new Business();
        // business.active();
        System.out.println("it's finished");
    }

     

  2. Background supplied to the variable page to be an exclamation mark, $ {var} - intermediate exclamation mark! . Note: If var = null or not present, then the $ {var} will be displayed directly on the page
    <input type="text" name="email" value="$!email"/>
    <input type="text" name="email" value="$!{email}"/>

     

  3. Braces must be used if / else / for / while / do statement, even if only one line of code, avoiding the use of the following form: if (condition) statements;
  4. In subList scenario, the high degree of attention modification of the original list, will lead to traverse the sub-lists, add, delete all ConcurrentModificationException produce abnormal;
    Note: The reason can be seen from the source, when the sub-list add and delete elements, add and delete accordingly this list. But on the contrary there will be an exception. As for why such a design Java, is not known.

     

    Negative example:                
       List<String> originList = new ArrayList<String>();
       originList.add("22");
       List<String> subList = originList.subList(0, 1);
       //warn
       originList.add("22"); 

     

  5. In a switch block, or in each case terminated by a break / return, etc., or explanatory notes to which the program will continue until the case; within a switch block, must contain a default statement and placed at the end, even though it What the code does not.

  6. When using regular expressions, make good use of its pre-compiled function, can effectively accelerate the speed of a regular match. Note: Do not vivo method defined: Pattern pattern = Pattern.compile (rule);
    NOTE: the code efficiency considerations

     

    public class XxxClass {
        // Use precompile
        private static Pattern NUMBER_PATTERN = Pattern.compile("[0-9]+");
        public Pattern getNumberPattern() {
            // Avoid use Pattern.compile in method body.
            Pattern localPattern = Pattern.compile("[0-9]+");
            return localPattern;
        }
    }

     

  7. When the multi-threaded parallel processing timing task, when Timer running multiple TimeTask, as long as one does not catch exceptions thrown, other tasks will automatically terminate, use ScheduledExecutorService is not the problem.
    NOTE: When processing a plurality of tasks in parallel, if desired thread exception does not affect each other, instead of using ScheduledExecutorService Timer

     

    //org.apache.commons.lang3.concurrent.BasicThreadFactory
    ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1,
            new BasicThreadFactory.Builder().namingPattern("example-schedule-pool-%d").daemon(true).build());
    executorService.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            //do something
        }
    },initialDelay,period, TimeUnit.HOURS);

     

  8. Defining DO / DTO / VO POJO class, etc., do not add any attribute default values. (Note: with the front of the packaging with the same strain)
  9. For Service and DAO classes, based on the concept of SOA, must be exposed service interfaces, internal implementation class with the suffix Impl differs Interface
    Note: SOA: Service-oriented architecture (Service-Oriented Architecture)
     
  10. Named constants should be all uppercase, separated by an underscore between words, semantic integrity and strive to clear, not too long name
    public class ConstantNameDemo {
    
    /**
    * max stock count
    */
    public static final Long MAX_STOCK_COUNT = 50000L;
     

     

  11. Exception exception class named using ends
  12. Loop body, the coupling of the character string using the StringBuilder append extension method.
  13. ThreadLocal variable must be recycled custom, especially in the thread pool scene, threads often be reused, if you do not clean up ThreadLocal variable custom, may affect subsequent business logic and cause memory leaks and other problems. Make use of try-finally block agent recovered.

  14. All comparison between the wrapper class object values, all compared using the equals method.
    说明:对于Integer var=?在-128至127之间的赋值,Integer对象是在IntegerCache.cache产生,会复用已有对象,这个区间内的Integer值可以直接使用==进行判断,
    但是这个区间之外的所有数据,都会在堆上产生,并不会复用已有对象,这是一个大坑,推荐使用equals方法进行判断。
                
        Integer a = 235;
        Integer b = 235;
        if (a.equals(b)) {
            //相等
        }

     

  15. All the abstract methods (including interface methods) must be used javadoc comments, in addition to the return values, parameters, exceptions stated, it must be noted that the method to do something, to achieve what functions. Note: If the implementation and deployment considerations, please also explain.
    /**
         * fetch data by rule id
         * 
         * @param ruleId rule id
         * @param page page number
         * @param jsonContext json format context
         * @return Result<XxxxDO>
         */
        Result<XxxxDO> fetchDataByRuleId(Long ruleId, Integer page, String jsonContext);

     

  16. All comments must be enumerated type field, indicating the purpose of each data item.
  17. All classes must be added the creator information.
  18. All the override method, you must add @Override comment. (Note: You can let the compiler errors are found in advance)
  19. All programming related names can not begin with an underscore, or dollar sign
  20. Abstract class name or the beginning of the use Abstract Base
  21. The method of internal single-line comments, annotated above statement on a separate line, using // comments. Internal multi-line comments using the / * * / comment. Note that the code is aligned.
  22. Method name, parameter name, member variables, local variables are consistent use lowerCamelCase, must comply hump form
  23. Note Math.random () This method returns a double type, attention range of values ​​[0, 1) (can be taken to a zero value, zero exception noted), if you want to acquire the random number integer type, do not enlarge x 10 several times and then rounding, nextInt or direct method using Random nextLong object. 
    Negative example:
        Long randomLong =(long) (Math.random() * 10);
    
            
    Positive example:
        Long randomLong = new Random().nextLong();
     
  24. Test class named after the name of its class to be tested beginning to end Test
  25. Class, class properties, class methods must be annotated using javadoc specification, use / ** * content / format may not be used // xxx mode and / * xxx * / way.

     

    
    说明:在IDE编辑窗口中,javadoc方式会提示相关注释,生成javadoc可以正确输出相应注释;在IDE中,工程调用方法时,不进入方法即可悬浮提示方法、参数、返回值的意义,提高阅读效率。
        /**
         * 
         * XXX class function description.
         *
         */
        public class XxClass implements Serializable {
            private static final long serialVersionUID = 113323427779853001L;
            /**
             * id
             */
            private Long id;
            /**
             * title
             */
            private String title;
        
            /**
             * find by id
             * 
             * @param ruleId rule id
             * @param page start from 1
             * @return Result<Xxxx>
             */
            public Result<Xxxx> funcA(Long ruleId, Integer page) {
                return null;
            }
        }

     

  26. Use UpperCamelCase style class name, must comply with the hump form, but the following exceptional circumstances related :( named domain model) DO / BO / DTO / VO / DAO
  27. Executors thread pool are not allowed to create, but by ThreadPoolExecutor way, this approach allows the students to write more explicit operating rules thread pool, to avoid the risk of resource depletion. 
    说明:Executors各个方法的弊端:
    1)newFixedThreadPool和newSingleThreadExecutor:
      主要问题是堆积的请求处理队列可能会耗费非常大的内存,甚至OOM。
    2)newCachedThreadPool和newScheduledThreadPool:
      主要问题是线程数最大数是Integer.MAX_VALUE,可能会创建数量非常多的线程,甚至OOM。
                
    Positive example 1:
        //org.apache.commons.lang3.concurrent.BasicThreadFactory
        ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1,
            new BasicThreadFactory.Builder().namingPattern("example-schedule-pool-%d").daemon(true).build());
           
            
                
    Positive example 2:
        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
            .setNameFormat("demo-pool-%d").build();
    
        //Common Thread Pool
        ExecutorService pool = new ThreadPoolExecutor(5, 200,
             0L, TimeUnit.MILLISECONDS,
             new LinkedBlockingQueue<Runnable>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());
    
        pool.execute(()-> System.out.println(Thread.currentThread().getName()));
        pool.shutdown();//gracefully shutdown
           
            
                
    Positive example 3:
        <bean id="userThreadPool"
            class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
            <property name="corePoolSize" value="10" />
            <property name="maxPoolSize" value="100" />
            <property name="queueCapacity" value="2000" />
    
        <property name="threadFactory" value= threadFactory />
            <property name="rejectedExecutionHandler">
                <ref local="rejectedExecutionHandler" />
            </property>
        </bean>
        //in code
        userThreadPool.execute(thread);

     

  28. Gets the current number of milliseconds: System.currentTimeMillis (); instead new Date () getTime (); .
    Note: This is the efficiency considerations, DAT objects without generating redundant
  29. 说明:如果想获取更加精确的纳秒级时间值,用System.nanoTime。在JDK8中,针对统计时间等场景,推荐使用Instant类。
        public class TimeMillisDemo {
            public static void main(String args[]) {
                // Positive example:
                long a = System.currentTimeMillis();
                // Negative example:
                long b = new Date().getTime();
        
                System.out.println(a);
                System.out.println(b);
            }
        }
     

    Return type of basic data types, the object is packaged return data type, there may be generated automatically unpacking NPE

    public int method() {
            Integer a = null;
            return a;
        }

     

  30. Avoid Random instance is using multiple threads, although sharing the instance is thread-safe, but due to competing for the same seed performance deterioration. Description: Random includes instances java.util.Random or Math.random () manner.
    说明:使用线程池的好处是减少在创建和销毁线程上所花的时间以及系统资源的开销,解决资源不足的问题。如果不使用线程池,有可能造成系统创建大量同类线程而导致消耗完内存或者“过度切换”的问题。
                
        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
        .setNameFormat("demo-pool-%d").build();
        ExecutorService singleThreadPool = new ThreadPoolExecutor(1, 1,
        0L, TimeUnit.MILLISECONDS,
        new LinkedBlockingQueue<Runnable>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());
    
        singleThreadPool.execute(()-> System.out.println(Thread.currentThread().getName()));
        singleThreadPool.shutdown();
         
  31. Avoid copy attributes using Apache Beanutils.

    说明:Apache BeanUtils性能较差,可以使用其他方案比如Spring BeanUtils, Cglib BeanCopier。
        TestObject a = new TestObject();
        TestObject b = new TestObject();
        a.setX(b.getX());
        a.setY(b.getY());

     

  32. Avoid such a static variable or static method to access, increase unnecessary analytical costs compiler, with direct access to the class name to a class of objects by reference. (Note: The need to understand the mechanisms JVM)
  33. In addition to common methods (e.g. getXxx / isXxx), etc., the condition is determined not to perform the complex sentence, determines the result of a complex logic is assigned to a boolean variable meaningful to improve readability.
    说明:很多if语句内的逻辑相当复杂,阅读者需要分析条件表达式的最终结果,才能明确什么样的条件执行什么样的语句,那么,如果阅读者分析逻辑表达式错误呢?
                
    Negative example:
        if ((file.open(fileName, "w") != null) && (...) || (...)) {
            ...
        }
                
            
                
    Positive example:
        boolean existed = (file.open(fileName, "w") != null) && (...) || (...);
        if (existed) {
            ...
        }
     
  34. When a set of initialization, the initial value of a specified set size.
    说明:HashMap使用如下构造方法进行初始化,如果暂时无法确定集合大小,那么指定默认值(16)即可。
             
     Negative example:   
       Map<String, String> map = new HashMap<String, String>();
        
            
     Positive example: 
       Map<String, String> map = new HashMap<String, String>(16);
     
Released nine original articles · won praise 4 · views 10000 +

Guess you like

Origin blog.csdn.net/juan190755422/article/details/85340457