You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

面试题:如何设计父类A确保子类doSomething()方法线程安全?

Solution to the Parent Class Design Interview Question

Nice question—this is a great test of how you balance inheritance rules, thread safety guarantees, and Java’s under-the-hood constructor behavior. Let’s walk through a solution that hits all the requirements, leveraging the hint about using the parent class constructor.

Key Requirements Recap

  • Subclasses must override doSomething()
  • Overridden doSomething() must be thread-safe
  • Subclasses can implement custom logic in the method
  • All logic lives in parent class A (we can't modify subclasses)

The Approach

First, we use an abstract class with an abstract doSomething() to enforce that subclasses override the method (this is your initial correct idea). Then, to guarantee thread safety, we use reflection in A's constructor to validate that the subclass's doSomething() implementation meets thread safety rules. Here's the code:

public abstract class A {
    // Abstract method forces subclasses to override doSomething() at compile time
    public abstract void doSomething();

    protected A() {
        try {
            // Get the doSomething() method from the actual subclass instance
            Method doSomethingMethod = this.getClass().getMethod("doSomething");
            
            // Check if the method is marked with synchronized
            boolean isSynchronized = Modifier.isSynchronized(doSomethingMethod.getModifiers());
            
            if (!isSynchronized) {
                throw new IllegalStateException("Subclass implementation of doSomething() must be thread-safe (use synchronized modifier)");
            }
        } catch (NoSuchMethodException e) {
            // This should never happen since the abstract method enforces overriding
            throw new RuntimeException("Subclass failed to override doSomething()", e);
        }
    }
}

How This Works

  1. Enforcing Overrides: By making A abstract and doSomething() an abstract method, Java will throw a compile error if any subclass doesn’t provide an implementation—this covers requirement #1 perfectly.
  2. Thread Safety Check: In A's constructor, we use this.getClass() to access the actual subclass's class definition. We then reflectively check if the subclass's doSomething() has the synchronized modifier. If not, we throw an exception to prevent the subclass from being instantiated, satisfying requirement #2.
  3. Custom Logic: Subclasses can write any code inside their synchronized doSomething() method, so requirement #3 is fully satisfied.

Notes on Limitations

This solution checks for the synchronized modifier, which is the most straightforward way to make a method thread-safe. If a subclass uses other thread-safe mechanisms (like java.util.concurrent.Lock), this check will flag it as invalid. For an interview setting, though, this is a clean, compliant solution that demonstrates your understanding of reflection, constructor execution order, and thread safety basics.

内容的提问来源于stack exchange,提问作者QuackDuck

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:04:20