简体   繁体   English

覆盖Java中的同步方法

[英]Overriding synchronized methods in Java

Let's say I have a synchronized method on some class: 假设我在某个类上有一个synchronized方法:

abstract class Foo {
    public synchronized void foo() {  // synchronized!
        // ...
    };
}

and I overrode it without using the synchronized modifier: 并且我在使用synchronized修饰符的情况下覆盖它:

class Bar extends Foo {
    @Override
    public void foo() {               // NOT synchronized!
        super.foo();
        // ...
    }
 }

I have a couple of specific question regarding this scenario: 关于这种情况,我有几个具体的问题:

  1. Will the overridden method be implicitly synchronized as well? 被覆盖的方法也会被隐式同步吗?
  2. If not, will the super -call be synchronized? 如果没有, super调用会同步吗?
  3. If there is no super -call, will anything be synchronized? 如果没有super呼叫,是否会同步?
  4. Is there a way to force an overriding method to use synchronized (I noticed that abstract method definitions or method definitions inside an interface don't allow the synchronized keyword)? 有没有办法强制重写方法使用synchronized (我注意到接口内的抽象方法定义或方法定义不允许synchronized关键字)?
public synchronized void foo() {  // synchronized!
    // ...
};

Is essentially the same as: 基本上与以下相同:

public void foo() {
    synchronized (this) {  // synchronized!
        // ...
    }
};

The latter is more explicit, so I would generally suggest using that form. 后者更明确,所以我通常建议使用该表格。 Or better using a lock that is a private field instead of the "outer" object. 或者更好地使用私有字段而不是“外部”对象的锁。

So: 1. No. 2. Yes. 所以:1。不.2。是的。 3. No. 4. Mark the method final and call a protected method that may be overridden. 3.否。标记方法final并调用可能被覆盖的protected方法。

public final void foo() {
    synchronized (this) {
        fooImpl();
    }
};
protected void fooImpl() {
    // ...
}

As ever, you may well be better off with delegation rather than subclassing. 和往常一样,你可能会更好地使用委托而不是子类化。

Failing to use synchronized when overriding a synchronized method has the potential for causing runtime bugs. 覆盖同步方法时未能使用synchronized可能会导致运行时错误。 As a safeguard, there is an Eclipse checker you can turn on to detect this condition. 作为安全措施,您可以打开Eclipse检查程序来检测此情况。 The default is "ignore". 默认为“忽略”。 "Warning" is also a valid choice. “警告”也是一个有效的选择。 喜好

which will produce this message: 这会产生这样的信息:

在此输入图像描述

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM