阿里Java开发规约(2)
生活随笔
收集整理的這篇文章主要介紹了
阿里Java开发规约(2)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
本文是對阿里插件中規約的詳細解釋二,關于插件使用,請參考這里
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"); }
<input type="text" name="email" value="$!email"/> <input type="text" name="email" value="$!{email}"/>
注:原因從源碼可以看出,當子list添加刪除元素時,也會相應添加刪除本list。但反之就會出現異常。至于Java為何要這樣設計,不得而知。
Negative example: List<String> originList = new ArrayList<String>();originList.add("22");List<String> subList = originList.subList(0, 1);//warnoriginList.add("22");
在一個switch塊內,每個case要么通過break/return等來終止,要么注釋說明程序將繼續執行到哪一個case為止;在一個switch塊內,都必須包含一個default語句并且放在最后,即使它什么代碼也沒有。
注:為代碼效率考慮
public class XxxClass {// Use precompileprivate 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;} }
多線程并行處理定時任務時,Timer運行多個TimeTask時,只要其中之一沒有捕獲拋出的異常,其它任務便會自動終止運行,使用ScheduledExecutorService則沒有這個問題。
注:當處理多個并行任務時,如果需要線程異常不互相影響,用ScheduledExecutorService代替Timer
注:SOA:面向服務架構(Service-Oriented Architecture)
public class ConstantNameDemo {/** * max stock count */ public static final Long MAX_STOCK_COUNT = 50000L;
必須回收自定義的ThreadLocal變量,尤其在線程池場景下,線程經常會被復用,如果不清理自定義的 ThreadLocal變量,可能會影響后續業務邏輯和造成內存泄露等問題。盡量在代理中使用try-finally塊進行回收。
說明:對于Integer var=?在-128至127之間的賦值,Integer對象是在IntegerCache.cache產生,會復用已有對象,這個區間內的Integer值可以直接使用==進行判斷,
但是這個區間之外的所有數據,都會在堆上產生,并不會復用已有對象,這是一個大坑,推薦使用equals方法進行判斷。Integer a = 235;Integer b = 235;if (a.equals(b)) {//相等}
/*** 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);
Negative example:Long randomLong =(long) (Math.random() * 10);Positive example:Long randomLong = new Random().nextLong();
說明:在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;}}
說明:Executors各個方法的弊端: 1)newFixedThreadPool和newSingleThreadExecutor:主要問題是堆積的請求處理隊列可能會耗費非常大的內存,甚至OOM。 2)newCachedThreadPool和newScheduledThreadPool:主要問題是線程數最大數是Integer.MAX_VALUE,可能會創建數量非常多的線程,甚至OOM。Positive example 1://org.apache.commons.lang3.concurrent.BasicThreadFactoryScheduledExecutorService 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 PoolExecutorService 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);
注:這是從效率考慮,不用生成冗余的DAT對象
返回類型為基本數據類型,return包裝數據類型的對象時,自動拆箱有可能產生NPE
public int method() {Integer a = null;return a;}說明:使用線程池的好處是減少在創建和銷毀線程上所花的時間以及系統資源的開銷,解決資源不足的問題。如果不使用線程池,有可能造成系統創建大量同類線程而導致消耗完內存或者“過度切換”的問題。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();
避免用Apache Beanutils進行屬性的copy。
說明:Apache BeanUtils性能較差,可以使用其他方案比如Spring BeanUtils, Cglib BeanCopier。TestObject a = new TestObject();TestObject b = new TestObject();a.setX(b.getX());a.setY(b.getY());說明:很多if語句內的邏輯相當復雜,閱讀者需要分析條件表達式的最終結果,才能明確什么樣的條件執行什么樣的語句,那么,如果閱讀者分析邏輯表達式錯誤呢?Negative example:if ((file.open(fileName, "w") != null) && (...) || (...)) {...}Positive example:boolean existed = (file.open(fileName, "w") != null) && (...) || (...);if (existed) {...}
說明:HashMap使用如下構造方法進行初始化,如果暫時無法確定集合大小,那么指定默認值(16)即可。Negative example: Map<String, String> map = new HashMap<String, String>();Positive example: Map<String, String> map = new HashMap<String, String>(16);
轉載于:https://www.cnblogs.com/roostinghawk/p/8110335.html
總結
以上是生活随笔為你收集整理的阿里Java开发规约(2)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 团队绩效博客
- 下一篇: javascript严格模式