如何确保覆盖的方法同步 [英] How can I ensure that an overridden method is synchronized
问题描述
我有一类常见的代码是线程安全的。
该类中的一个方法是抽象的,需要为不同的实现重写。 p>
我需要确保或至少标记其他开发人员,该方法的所有实现都需要线程安全。
这是最好的方法是什么?
这个效果有关键字或注释吗?
我已经尝试过抽象同步
,但不允许使用关键字组合。
你不能直接做。你可以做的一件事是具体的方法,但调用一个抽象的方法:
public synchronized final void foo
doFoo();
}
protected abstract void doFoo();
这样,doFoo()将始终在foo / p>
*,除非有人直接调用它,因此您应该命名和记录它,以表明它们不应该。
I have a class of common code that is thread safe.
One of the methods in that class is abstract and needs to be overridden for different implementations.
I need to ensure or at least flag to other developers that all implementations of this method need to be thread-safe.
What is the best way to do this?
Is there a keyword or annotation to this effect?
I have already tried abstract synchronized
but that combination of keywords is not allowed.
You can't do it directly. One thing you can do is have the method be concrete, but invoke an abstract method:
public synchronized final void foo() {
doFoo();
}
protected abstract void doFoo();
That way, doFoo() will always* be invoked under the synchronization established by foo().
* unless someone invokes it directly, so you should name and document it to make it clear that they shouldn't.
这篇关于如何确保覆盖的方法同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!