How can I ensure that an overridden method is synchronized

前端 未结 3 493
傲寒
傲寒 2021-02-02 09:59

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

3条回答
  •  时光说笑
    2021-02-02 10:34

    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.

提交回复
热议问题