如何确保超类的子类方法的线程安全? [英] How to ensure Thread safety of subclass' methods from a superclass?

查看:134
本文介绍了如何确保超类的子类方法的线程安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我参加了一次面试,并被要求设计一个符合以下要求的课程. 假设我有一个A类,它可以有任意数量的子类,即子类. 类A有一个称为doSomething()的方法,该方法已同步.要求是:

I attended an interview and I was asked to design a class for the following requirement. Assume I have a class A and it can have any number of children, i.e., subclasses. The class A has a method called doSomething() which is synchronized. The requirements are :

  1. 强制所有A 的子类都覆盖doSomething()方法.

所有子类的重写doSomething()方法本质上必须是线程安全的.

All subclasses' overriden doSomething() method must be Thread safe in nature.

所有子类的doSomething()方法实现都必须具有规定以实现自己的逻辑.

All subclasses' must have the provision to implement their own logic for their doSomething() method implementations.

A类的构造函数由我决定(设计者)来决定如何实现.

Class A's constructor is upto me(the designer) to decide how to implement.

设计者无法控制要创建多少个子类或如何创建子类,即,设计者只能为超类编写代码.

The designer has no control on how many subclasses would be created or how they would be created,i.e., the designer can only write code for the superclass only.


我建议将类抽象化,并将doSomething()方法抽象化.这意味着扩展我的类的类必须提供自己的doSomething()方法.


I suggested to make the class abstract and also the doSomething() method abstract. This would imply classes extending my class necessarily provide their own doSomething() method.

但是,我无法回答我的类A到底能确保子类的线程安全以及doSomething()方法的安全性.

However, I could not answer as to what exactly in my class A would ensure Thread safety for my child classes and that too just for the doSomething() method.

尽管他给出了一个提示,但他说这是在A类的构造函数中完成的.

有什么想法吗?

推荐答案

我想说最好使basedoSomething方法public final synchronized(final确保子类不能覆盖它)和调用另一个protected abstract方法. public synchronized final void doSmoething确保any calldoSomething的方法将是synchronized / thread safe,而doSmoethingImpl抽象方法将提供灵活性,以便在子类中为该方法提供自己的定义.

I would say better to make the base class doSomething method public final synchronized (final to make sure subclass can't override it) and call another protected abstract method. public synchronized final void doSmoething ensure that any call to doSomething method will be synchronized / thread safe and doSmoethingImpl abstract method will provide flexibility to give the method own definition in a subclass.

abstract class A {
    public synchronized final void doSmoething() {
        doSmoethingImpl();
    }
    protected abstract void doSmoethingImpl();


}

class B extends A {
    @Override
    protected void doSmoethingImpl() {
        // definition in class B
    }
}

注意:上述解决方案不会直接满足您的第1点要求,但doSmoethingImpl()将为您提供间接实现类似功能的范围.

Note: Above solution will not directly satisfy your point 1 but doSmoethingImpl() will give you scope to achieve the similar functionality indirectly.

这篇关于如何确保超类的子类方法的线程安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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