# P3C-PMD
## <font color="green">Build requirements</font>
- JDK 1.7+
- Maven 3
## <font color="green">Use as dependency</font>
### <font color="green">Maven</font>
```xml
<dependency>
<groupId>com.alibaba.p3c</groupId>
<artifactId>p3c-pmd</artifactId>
<version>1.3.0</version>
</dependency>
```
### <font color="green">Gradle</font>
```groovy
compile 'com.alibaba.p3c:p3c-pmd:1.3.0'
```
## <font color="green">Rules</font>
P3C-PMD implements 49 rules involved in *Alibaba Java Coding Guidelines*, based on PMD ([https://github.com/pmd/pmd](https://github.com/pmd/pmd)).
### <font color="green">Concurrency</font>
* 1 ``[Mandatory]`` Customized ThreadLocal variables must be recycled, especially when using thread pools in which threads are often reused. Otherwise, it may affect subsequent business logic and cause unexpected problems such as memory leak.
* 2 ``[Mandatory]`` A meaningful thread name is helpful to trace the error information, so assign a name when creating threads or thread pools.
Positive example:
```java
public class TimerTaskThread extends Thread {
public TimerTaskThread(){
super.setName("TimerTaskThread"); … }
```
* 3 ``[Mandatory]`` Threads should be provided by thread pools. Explicitly creating threads is not allowed.
Note: Using thread pool can reduce the time of creating and destroying thread and save system resource. If we do not use thread pools, lots of similar threads will be created which lead to "running out of memory" or over-switching problems.
* 4 ``[Mandatory]`` A thread pool should be created by ThreadPoolExecutor rather than Executors. These would make the parameters of the thread pool understandable. It would also reduce the risk of running out of system resources.
Note: Below are the problems created by usage of Executors for thread pool creation:
1. FixedThreadPool and SingleThreadPool:
Maximum request queue size Integer.MAX_VALUE. A large number of requests might cause OOM.
2. CachedThreadPool and ScheduledThreadPool:
The number of threads which are allowed to be created is Integer.MAX_VALUE. Creating too many threads might lead to OOM.
* 5 ``[Mandatory]`` SimpleDataFormat is unsafe, do not define it as a static variable. If you have to, lock or Apache DateUtils class must be used.
Positive example: Pay attention to thread-safety when using DateUtils. It is recommended to use below:
```java
private static final ThreadLocal<DateFormat> df = new ThreadLocal<DateFormat>() {
@Override
protected DateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd");
}
};
```
Note: In JDK8, Instant can be used to replace Date; likewise Calendar is replaced by LocalDateTime, and SimpleDateFormatter is replaced by DateTimeFormatter.
* 6 ``[Mandatory]`` Run multiple TimeTask by using ScheduledExecutorService rather than Timer, because Timer will kill all running threads in case of failure to catch exceptions.
* 7 ``[Recommended]`` When using CountDownLatch to convert asynchronous operations to synchronous ones, each thread must call countdown method before quitting. Make sure to catch any exception during thread running, to let countdown method be executed. If main thread cannot reach await method, program will return until timeout.
Note: Be careful, exception thrown by a child thread cannot be caught by main thread.
* 8 ``[Recommended]`` Avoid using Random instance by multiple threads. Although it is thread-safe, competition on the same seed will damage performance.
Note: Random instance includes instances of java.util.Random and Math.random().
Positive example:
After JDK7, ThreadLocalRandom API can be used directly. But before JDK7, instance needs to be created in each thread.
### <font color="green">Collection</font>
* 1 ``[Mandatory]`` Do not cast subList in class ArrayList, otherwise ClassCastException will be thrown: java.util.RandomAccessSubList cannot be cast to java.util.ArrayList.
Note: subList of ArrayList is an inner class, which is a view of ArrayList. All operations on the Sublist will affect the original list finally.
* 2 ``[Mandatory]`` When using subList, be careful while modifying the size of original list. It might cause ConcurrentModificationException when performing traversing, adding or deleting on the subList.
* 3 ``[Mandatory]`` Use toArray(T[] array) to convert list to array. The input array type should be the same with the list whose size is list.size().
Counter example: Do not use toArray method without arguments. Since the return type is Object[], ClassCastException will be thrown when casting it to a different array type.
Positive example:
```java
List<String> list = new ArrayList<String>(2);
list.add("guan");
list.add("bao");
String[] array = new String[list.size()];
array = list.toArray(array);
```
Note: When using toArray method with arguments, if input array size is not large enough, the method will re-assign the size internally, and then return the address of new array. If the size is larger than needed, the value of index[list.size()] will be set to null while other values remain the same. Defining an input with the same size of the list is recommended.
* 4 ``[Mandatory]`` Do not use methods which will modify the list after using Arrays.asList to convert array to list, otherwise methods like add/remove/clear will throw UnsupportedOperationException.
Note: The result of asList is the inner class of Arrays, which does not implement methods to modify itself. Arrays.asList is only a transferred interface, data inside which is stored as an array.
```java
String[] str = new String[] { "a", "b" };
List<String> list = Arrays.asList(str);
```
Case 1: list.add("c"); will throw a runtime exception.
Case 2: str[0]= "gujin"; list.get(0) will be modified.
* 5 ``[Mandatory]`` Do not remove or add elements to a collection in a foreach loop. Please use Iterator to remove an item. Iterator object should be synchronized when executing concurrent operations.
Counter example:
```java
List<String> a = new ArrayList<String>();
a.add("1");
a.add("2");
for (String temp : a) {
if ("1".equals(temp)) {
a.remove(temp);
}
}
```
Note: If you try to replace "1" with "2", you will get an unexpected result.
Positive example:
```java
Iterator<String> it = a.iterator();
while (it.hasNext()) {
String temp = it.next();
if (delete condition) {
it.remove();
}
}
```
* 6``[Recommended]`` Set a size when initializing a collection if possible.
Note: Better to use ArrayList(int initialCapacity) to initialize ArrayList.
### <font color="green">Naming Conventions</font>
* 1 ``[Mandatory]`` No identifier name should start or end with an underline or a dollar sign.
Counter example: _name / __name / $Object / name_ / name$ / Object$
* 2 ``[Mandatory]`` Using Chinese, Pinyin, or Pinyin-English mixed spelling in naming is strictly prohibited. Accurate English spelling and grammar will make the code readable, understandable, and maintainable.
Positive example: alibaba / taobao / youku / Hangzhou. In these cases, Chinese proper names in Pinyin are acceptable.
* 3 ``[Mandatory]`` Class names should be nouns in UpperCamelCase except domain models: DO, BO, DTO, VO, etc.
Positive example: MarcoPolo / UserDO / HtmlDTO / XmlService / TcpUdpDeal / TaPromotion
Counter example: macroPolo / UserDo / HTMLDto / XMLService / TCPUDPDeal / TAPromotion
* 4 ``[Mandatory]`` Method names, parameter names, member variable names, and local variable names should be written in lowerCamelCase.
Positive example: localValue / getHttpMessage() / inputUserId
* 5 ``[Mandatory]`` Constant variable names should be written in upper characters separated
没有合适的资源?快使用搜索试试~ 我知道了~
Java开发手册(阿里巴巴带-alibaba-IDE插件)
共316个文件
kt:88个
java:81个
xml:81个
需积分: 9 13 下载量 48 浏览量
2018-01-27
21:05:45
上传
评论
收藏 15.51MB ZIP 举报
温馨提示
《阿里巴巴Java开发手册》是阿里内部Java工程师所遵循的开发规范,涵盖编程规约、单元测试规约、异常日志规约、MySQL规约、工程规约、安全规约等,这是近万名阿里Java技术精英的经验总结,并经历了多次大规模一线实战检验及完善。这是阿里回馈给Java社区的一份礼物,希望能够帮助企业开发团队在Java开发上更高效、容错、有协作性,提高代码质量,降低项目维护成本。
资源推荐
资源详情
资源评论
收起资源包目录
Java开发手册(阿里巴巴带-alibaba-IDE插件) (316个子文件)
gradlew.bat 2KB
StaticDescriptionTemplate.ftl 243B
blocker.gif 605B
critical.gif 219B
clear.gif 163B
.gitignore 886B
.gitignore 825B
.gitignore 824B
.gitignore 815B
build.gradle 3KB
build.gradle 908B
build.gradle 556B
settings.gradle 40B
gradlew 5KB
gradle-wrapper.jar 53KB
FixClassTypeResolver.java 29KB
CommentsMustBeJavadocFormatRule.java 10KB
IbatisMethodQueryForListRule.java 8KB
AvoidManuallyCreateThreadRule.java 7KB
AvoidCallStaticSimpleDateFormatRule.java 7KB
RemoveCommentedCodeRule.java 7KB
AbstractMethodOrInterfaceMethodMustUseJavadocRule.java 7KB
EqualsAvoidNullRule.java 6KB
StringConcatRule.java 6KB
MethodReturnWrapperTypeRule.java 6KB
I18nResources.java 5KB
AvoidConcurrentCompetitionRandomRule.java 5KB
ThreadShouldSetNameRule.java 5KB
PojoMustOverrideToStringRule.java 5KB
UnsupportedExceptionWithModifyAsListRule.java 5KB
UndefineMagicConstantRule.java 5KB
ThreadPoolCreationRule.java 4KB
TransactionMustHaveRollbackRule.java 4KB
ConcurrentExceptionWithModifyOriginSubListRule.java 4KB
ThreadLocalShouldRemoveRule.java 4KB
UseQuietReferenceNotationRule.java 4KB
AvoidCommentBehindStatementRule.java 4KB
ClassMustHaveAuthorRule.java 3KB
ClassCastExceptionWithToArrayRule.java 3KB
DontModifyInForeachCircleRule.java 3KB
TestClassShouldEndWithTestNamingRule.java 3KB
ConstantFieldShouldBeUpperCaseRule.java 3KB
CollectionInitShouldAssignCapacityRule.java 3KB
SwitchStatementRule.java 3KB
EnumConstantsMustHaveCommentRule.java 3KB
NeedBraceRule.java 3KB
PojoMustUsePrimitiveFieldRule.java 3KB
LowerCamelCaseVariableNamingRule.java 3KB
NameListServiceImpl.java 3KB
CountDownShouldInFinallyRule.java 2KB
AvoidStartWithDollarAndUnderLineNamingRule.java 2KB
ExceptionClassShouldEndWithExceptionRule.java 2KB
PojoNoDefaultValueRule.java 2KB
WrapperTypeEqualityRule.java 2KB
AvoidPatternCompileInMethodRule.java 2KB
ClassNamingShouldBeCamelRule.java 2KB
ViolationUtils.java 2KB
ClassCastExceptionWithSubListToArrayListRule.java 2KB
NodeUtils.java 2KB
BooleanPropertyShouldNotStartWithIsRule.java 2KB
AbstractAliRule.java 2KB
AbstractPojoRule.java 2KB
AvoidUseTimerRule.java 2KB
GeneratedCodeUtils.java 2KB
AbstractClassShouldStartWithAbstractNamingRule.java 2KB
ServiceOrDaoClassShouldEndWithImplRule.java 2KB
AvoidMissUseOfMathRandomRule.java 2KB
AvoidNewDateGetTimeRule.java 2KB
AvoidComplexConditionRule.java 2KB
AbstractAliCommentRule.java 2KB
NamingRulesTest.java 2KB
AbstractXpathRule.java 2KB
PackageNamingRule.java 2KB
ArrayNamingShouldHaveBracketRule.java 2KB
SpiLoader.java 2KB
AvoidReturnInFinallyRule.java 2KB
UpperEllRule.java 2KB
AvoidApacheBeanUtilsCopyRule.java 2KB
PojoUtils.java 1KB
ConcurrentRuleTest.java 1KB
NodeSortUtils.java 1KB
SetRulesTest.java 1KB
CommentRulesTest.java 1KB
P3cIcons.java 1KB
NameListService.java 1KB
OopRuleTest.java 1KB
NumberConstants.java 1KB
OtherRulesTest.java 1KB
ExceptionRulesTest.java 1KB
NameListConfig.java 1KB
FlowControlRuleTest.java 1KB
ConstantRulesTest.java 1KB
OtherRulesTest.java 1KB
OrmRulesTest.java 1015B
StringAndCharConstants.java 958B
package-info.java 101B
CleanUps.kt 14KB
StyleExtractor.kt 10KB
AliCodeAnalysisCheckinHandler.kt 9KB
AliInspectionAction.kt 9KB
共 316 条
- 1
- 2
- 3
- 4
资源评论
mizone_1982
- 粉丝: 42
- 资源: 123
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功