gpt4 book ai didi

java - 避免在方法级别同步

转载 作者:行者123 更新时间:2023-12-02 02:43:45 25 4
gpt4 key购买 nike

PMD(源代码分析器)建议避免在方法级别进行同步。实际上很明显,当您在方法上调用 synchronized 时,您正在对 this 调用 Synchronized,这可能会导致潜在的问题。

但此规则中的 PMD 建议使用以下示例:Synchronized on method rule

public class Foo {
// Try to avoid this:
synchronized void foo() {
}
// Prefer this: <----- Why? Isn't it the same on byte-code level
void bar() {
synchronized(this) {
}
}
}

这是PMD规范中的错误(在示例中)还是synchronized on方法的工作方式与synchronized(this)不同?

最佳答案

是的,技术上是相同的。这是关于代码风格,而不是正确性。

您发布的链接很好地解释了原因:

Method-level synchronization can cause problems when new code is addedto the method. Block-level synchronization helps to ensure that onlythe code that needs synchronization gets it.

关于java - 避免在方法级别同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63132263/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com