我参加了一次面试,并被要求为以下要求设计一个课程。
假设我有一个 A 类,它可以有任意数量的子类,即子类。
类 A 有一个名为 doSomething() 的方法,该方法是同步的。要求是:
-
A 的所有子类都是强制性的重写 doSomething() method.
-
所有子类重写的 doSomething() 方法必须是线程安全的在自然界。
-
所有子类必须具有规定实现自己的逻辑他们的 doSomething() 方法实现。
-
A类的构造函数由我决定(设计者)决定如何实施。
设计者无法控制将创建多少子类或如何创建子类,即设计者只能为超类编写代码.
我建议将类和 doSomething() 方法抽象化。这意味着扩展我的类的类必须提供自己的 doSomething() 方法。
然而,我无法回答我的类 A 中到底有什么可以确保我的子类的线程安全,以及 doSomething() 方法的线程安全。
不过他给出了一个提示,他说这个技巧是在 A 类的构造函数中完成的。
有任何想法吗?
经过很长时间的研究我发现synchronization
如果方法被重写且未显式添加关键字,则无法继承synchronized
在重写方法的签名中!
因为这个问题主要是为了防止其他用户(即开发人员)违反您的类的使用(因为他们正在扩展它)。
我想出了一种方法来解决这个问题Reflection
Java 中的类。
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
public class A {
public A(){
assertSynch("doSomething");
}
// method to assert a particular method is synchronized in the subclass
private void assertSynch(String methodName) {
Class<? extends A> subclass = this.getClass(); // this returns the subclass
Method[] methods = subclass.getDeclaredMethods();
for (Method meth : methods) { // loop through the methods in subclass
if(meth.getName().equals(methodName)) { // when it reaches your method
String modVal = Modifier.toString(meth.getModifiers()); // get its modifier
if(!modVal.contains("synchronized")) { // check if it contains the keyword "synchronized"
try { // if not -> throw an Exception with clear message about the reason and exit
throw new Exception(methodName +
" must be synchronized to ensure class thread safety!");
} catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
}
}
}
}
public synchronized void doSomething() {}
}
public class B extends A{
public B() { } // it implicitly calls the superclass constructor
@Override
public void doSomething() { } // it will make the program to throw the above exception
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)