为什么抽象方法不能同步? [英] Why can't an abstract method be synchronized?

查看:202
本文介绍了为什么抽象方法不能同步?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读来自CodeRanch的线程说抽象方法无法同步,因为抽象类无法实例化,这意味着没有对象可以锁定。

I was reading a thread from CodeRanch saying that abstract methods could not be synchronized due to the fact that an abstract class cannot be instantiated, meaning no object to lock.

这没有意义抽象类是子类的定义(契约)。子进程的同步方法的抽象定义不需要锁定。所有抽象标题都表明子必须同步此方法。我的逻辑是否正确?如果没有,有人可以解释为什么我错了吗?

This doesn't make sense since an abstract class is a definition (contract) for a child class. The abstract definition of a synchronized method does not need to lock, the child does. All the abstract heading would indicate is that the child must synchronize this method. Is my logic on this correct? If not can someone explain why I'm wrong?

推荐答案

关于无法实例化抽象类的评论是垃圾。鉴于它必须是一个抽象的实例方法,肯定一个可以锁定的引用。抽象类中的具体方法仍然可以引用 this 。但是,这仍然不意味着抽象类应该能够同步。

The comment about not being able to instantiate the abstract class is garbage. Given that it has to be an instance method to be abstract, there certainly is a reference which could be locked on. Concrete methods in abstract classes can still refer to this. However, that still doesn't mean that abstract classes should be able to be synchronized.

方法是否同步是实现细节方法。同步未指定任何地方作为声明性合同 - 它不像你可以在接口中同步。

Whether or not a method is synchronized is an implementation detail of the method. Synchronization isn't specified anywhere as a declarative contract - it's not like you can synchronize in interfaces, either.

类如何实现任何线程它提供的安全保障取决于它。如果抽象类想要强制特定方法,它应该使用模板方法模式:

How a class implements whatever thread safety guarantees it provides is up to it. If an abstract class wants to mandate a particular approach, it should use the template method pattern:

// I hate synchronizing on "this"
private final Object lock = new Object();

public final void foo() {
    synchronized(lock) {
        fooImpl();
    }
}

protected abstract void fooImpl();

这本身就很危险,因为它在锁中有效地调用了未知代码,是一个死锁等的配方。

That's pretty dangerous in itself though, given that it's effectively calling "unknown" code within a lock, which is a recipe for deadlocks etc.

这篇关于为什么抽象方法不能同步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆