Java - 'synchronized' 和 'final' 方法,声明顺序
Java - 'synchronized' and 'final' method, declaration ordering
我对方法的 synchronized 和 final 的顺序有疑问。以下两个都被编译器接受,但它们之间有什么实际区别吗?
public synchronized final void update() {
// Do stuff
}
public final synchronized void update() {
// Do stuff
}
来自JLS 8.4.3 :
If two or more (distinct) method modifiers appear in a method declaration, it is customary, though not required, that they appear in the order consistent with that shown above in the production for MethodModifier.
并且生产 MethodModifier 顺序指定为(参见我提供的 JLS link):
MethodModifiers:
MethodModifier
MethodModifiers MethodModifier
MethodModifier: one of
Annotation public protected private abstract
static final synchronized native strictfp
所以JLS规定synchronized
和final
可以任意顺序出现。
因此,您的问题的答案是:没有区别。
当然,没有区别。
但是许多指南样式、框架、公司都提倡事实上的标准顺序,并且 checkstyle.sourceforge.io puts it, is recommended by the Java Language Specification (sections 8.1.1, 8.3.1, 8.4.3 and 9.4.)
public
protected
private
abstract
default
static
final
transient
volatile
synchronized
native
strictfp
我对方法的 synchronized 和 final 的顺序有疑问。以下两个都被编译器接受,但它们之间有什么实际区别吗?
public synchronized final void update() {
// Do stuff
}
public final synchronized void update() {
// Do stuff
}
来自JLS 8.4.3 :
If two or more (distinct) method modifiers appear in a method declaration, it is customary, though not required, that they appear in the order consistent with that shown above in the production for MethodModifier.
并且生产 MethodModifier 顺序指定为(参见我提供的 JLS link):
MethodModifiers:
MethodModifier
MethodModifiers MethodModifier
MethodModifier: one of
Annotation public protected private abstract
static final synchronized native strictfp
所以JLS规定synchronized
和final
可以任意顺序出现。
因此,您的问题的答案是:没有区别。
当然,没有区别。
但是许多指南样式、框架、公司都提倡事实上的标准顺序,并且 checkstyle.sourceforge.io puts it, is recommended by the Java Language Specification (sections 8.1.1, 8.3.1, 8.4.3 and 9.4.)
public protected private abstract default static final transient volatile synchronized native strictfp