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

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

问题描述

我正在阅读来自 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天全站免登陆